Reputation: 217
I am trying to write a regular expression that matches the a string with the following properties:
See examples below. I am using b
to represent a blank space character.
Valid examples
123 b12 bb1 1bb 12b
Invalid examples
bbb 1b2
I've tried
[0-9 ]{1, 3}
The above regular expression matches strings with all characters blank. Can someone help me with writing a better regular expression?
Upvotes: 3
Views: 38659
Reputation: 336158
I would use lookaheads for this:
^(?=.*\d)[\d ]{3}$
Explanation:
^ # Start of string
(?=.*\d) # Assert presence of at least one digit
[\d ]{3} # Match exactly three digits or spaces
$ # End of string
Upvotes: 9
Reputation: 46559
This should be written out in full. Furtunately, if you mean you want only numbers optionally preceded or followed by spaces (as seen from the 1b2
bit which isn't allowed), there is only a small number of possibilities.
([0-9] )|([0-9]{2} )|([0-9]{3})|( [0-9])|( [0-9]{2})
There you have it.
Of course, if you can do the checking for length=3 outside of the regex, the regex itself can be shortened to
([0-9]{1,3}[ ]*)|([ ]*[0-9]{1,3})
Upvotes: 5