AGEM
AGEM

Reputation: 217

Regex with blank characters

I am trying to write a regular expression that matches the a string with the following properties:

  1. Contains exactly 3 characters.
  2. Can contain blank spaces.
  3. At least one character should be non blank space.
  4. 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?

Upvotes: 3

Views: 38659

Answers (2)

Tim Pietzcker
Tim Pietzcker

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

Mr Lister
Mr Lister

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

Related Questions