Home > Mobile >  Regex to match substring containing 18 digits but don't match if it starts with @
Regex to match substring containing 18 digits but don't match if it starts with @

Time:12-31

I've looked for a solution and played around a bit with some examples but couldn't find what I'm looking for. (I'm using javascript)

Basically it should only match a string of 18 digits if the first character isn't @, it should only include the 18 digits.

So something like /[^@]\d{18}/g but if I do this it includes the first character that is not an @

Examples: test 123456789012345678 abc match 123456789012345678

test @123456789012345678 abc don't match.

CodePudding user response:

One option is to match an @ and a digit that you don't want, and then capture 18 digits between word boundaries \b in capture group 1 that you want to keep.

The word boundaries are to prevent a partial match for the digits.

@\d|\b(\d{18})\b

Regex demo

If supported, you can also use a negative lookbehind:

\b(?<!@)\d{18}\b

Regex demo

  • Related