I am trying to write a regular expression that matches the a string with the following properties:
- Contains exactly 3 characters.
- Can contain blank spaces.
- At least one character should be non blank space.
- Only blank spaces and digits are allowed.
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?
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
1b2bit which isn’t allowed), there is only a small number of possibilities.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