Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match comparison operators in Regex

Tags:

regex

I'm trying to create a regex that matches comparisons like this:

= 445
> 5
>= 22
< 3
<= 42
<> 10

I thought that this would work, but it doesn't:

[=|>|<|>=|<|<=|<>]\s\d+

It's very important that the '>' or '<' precede '='. These operators would not be valid:

=<
=>
>>
<<
==

I'm using this to create some dynamic sql so the comparison operators need to valid sql.

Any suggestions?

like image 389
Micah Avatar asked Feb 26 '10 18:02

Micah


3 Answers

(=|>|<|>=|<|<=|<>)\s\d+

or something like: (doesn't really do what you want, it matches all 2character combinations of =<>, but for clearness)

[=><]{1,2}\s\d+

-> when you use the [] braces, it means, that one of the character inside should take place (multiple | defined may lead to undefined behavior, or behavior I'm not aware of)

-> you probably wanted to use simple braces (), where the | has the 'OR' meaning.

like image 73
nothrow Avatar answered Oct 01 '22 08:10

nothrow


I would say the regex given by EmFi is good enough. With some modifications it can take expressions like this

"currentDate>=2012/11/07&&currentDate<=2012/11/08";

or this

"currentDate==2012/11/07";

With this modified regex

(<[=>]?|==|>=?|\&\&|\|\|)

And give it as "valid". Probably is very simple but at least in my case, enough

EDIT: Regex was modified in order to take comparison operators (<,>,>=,<=,==) and boolean operators (&&,||) in a similar way to C-like languages

like image 27
jchacana Avatar answered Oct 01 '22 09:10

jchacana


The syntax […] denotes a character class. Use (…) for grouping instead:

(=|>|<|>=|<|<=|<>)\s\d+

And here’s a more compact one:

(=|[<>]=?|<>)\s\d+

Or:

(=|<[>=]?|>=?)\s\d+
like image 22
Gumbo Avatar answered Oct 01 '22 08:10

Gumbo