1

I need a regular expression to validate strings with the prefix 'CON' followed by an optional space followed by 8 digits.

I've tried various expressions, I got tangled up and now I'm lost.

^(CON+s\?d{8})$

\bCON\b\S?D{8}
Joyc0025
  • 19
  • 1

3 Answers3

2

Syntax is off a bit

^(CON\s?\d{8})

( starts a capturing group
CON is exactly matched
\s matches any white space character and the ? makes it optional
\d{8} matches 8 digits
) ends the capturing group

You were pretty well off to start, Hope this helps :)

Ehsan O
  • 23
  • 4
  • Well done! This looks good to me. You have your first upvote from me. Welcome to the community. – YetAnotherBot Mar 13 '19 at 04:45
  • Haha thank you @AdityaGupta – Ehsan O Mar 13 '19 at 04:59
  • 1
    Capture group isn't needed if all OP is trying to just validate. Also this will match any string that starts with regex pattern which is not right as it will validate strings it should not. And `\s` will allow a tab or a newline which isn't what OP wants to allow as OP wants to just allow space. – Pushpesh Kumar Rajwanshi Mar 13 '19 at 05:09
0

keeping in mind If there is no space, then there shouldn't be 8 more digits

^CON(\ \d{8})?
0

If the string you are looking for can be part of a larger string (note that in this case it may be preceded or followed by anything, even other digits):

CON\s?\d{8}

If the string must match in full, use ^$ to designate that:

^CON\s?\d{8}$

You can add variations to it, if say you want it to begin/end with a word boundary - use \bto indicate that. If you want it to end in a non-digit, use \D+ at the end, instead of $.

Finally, if you want the string to end with an EOL or a non-digit, you may use an expression like this:

CON\s?\d{8}(\D+|$) or the same with a non-capturing group: CON\s?\d{8}(?:\D+|$)