Regular expression: combining statments with or operator

52 views Asked by At

I need a regular expression which roughly combines the logic of

?[1-9][0-9]+\s+X|x

with

X|x+\s*+[1-9][0-9]*

Or in english: match a pattern of the letter X (capitalised or uncapitalised) preceded by an integer (single space optional) OR succeeded by an integer (single space optional)

Thanks.

P.S. The two separate regex above are just for illustration; haven't actually tested them.

4

There are 4 answers

0
riddler On BEST ANSWER

You're nearly there, you need enclosing brackets to group as a capture group and to handle numbers other than those 2 digits long.

/([0-9]+\s{0,1}(X|x))|((X|x)\s{0,1}[0-9]+)/g

Paste it into http://regexr.com/ to try it out. I tested it with:

X9847 
X 2645
4442 x
x 525521
5254X5541
221 X 266
1
user2609980 On

This does exactly what you want:

(\d\s?[xX]{1}|[xX]{1}\s?\d)

Example

See http://regexr.com/.

Might not be the best regex.

0
Pruthvi Raj On

You said single space optional so i used \s?. If you can have any amount of whitespace, replace \s with \s* Try using this:

\d+\s?(X|x)|\s?\d+

DEMO

0
A.sharif On

This will work and matches specifically to your request: ((X|x)\s*\d+)|(\d+\s*(X|x))

Explanation:

(
  (X|x) First character must be an 'X' or 'x'
   \s*  Second character can be zero or infinite amount of spaces 
   \d+  Third character has to be one or more digits
)
|  or
(
  \d+   First character has to be one or more digits
  \s*   Second character can be zero or infinite amount of spaces
  (X|x) Third character must be an 'X' or 'x'
)