Reputation: 1048
I am buried in a RegExp hell and can't find way out, please help me.
I need RegExp that matches only numbers (at least 1 number) and one of this characters: <, >, = (exactly one of them one time).
My reg. expression looks like this:
^[0-9]+$|^[=<>]{1}$
And I thought it should match when my string containts one or more digits and exactly 1 special character defined by me. But it doesn't act correctly. I think there might be problem with my start/end of string definition but Im not sure about that.
Examples that should pass include:
<1
=2
22>
>1
=00123456789
Examples that should not pass this reg. exp.:
<<2
==222
<>=2
Upvotes: 2
Views: 624
Reputation: 149078
I thought it should match when my string containts one or more digits and exactly 1 special character
No, the original pattern matches a string contains one or more digits or exactly 1 special character. For example it will match 123
and =
but not 123=
.
Try this pattern:
^\d+[=<>]$
This will match that consists of one or more digits, followed by exactly one special character. For example, this will match 123=
but not 123
or =
.
If you want your special character to appear before the number, use a pattern like this instead:
^[=<>]\d+$
This will match =123
but not 123
or =
.
Update
Given the examples you provided, it looks like you want to match any string which contains one or more digits and exactly one special character either at the beginning or the end. In that case use this pattern:
^([=<>]\d+|\d+[=<>])$
This will match <1
, =2
, 22>
, and >1
, but not 123
or =
.
Upvotes: 2
Reputation: 106
This should work.
^[0-9]+[=<>]$
1 or more digits followed by "=<>".
Upvotes: 1
Reputation: 1887
Your regex says:
1 or more numbers OR 1 symbol
Also, the ^ and $ means the whole string, not contains. if you want a contains, drop them. I don't know if you have a space between the number and symbol, so put in a conditional space:
[0-9]+\s?[=<>]{1}
Upvotes: 1
Reputation: 11081
Just use [0-9]+[=<>]
Here are visualizers of your regexp and this one:
Upvotes: 1