Reputation: 3535
I need to match strings like the following:
( anything >= anything )
and there can by only these comparison operators: >= <= == != < > And they can be there only once. What I have is:
^\(.+(>=|<=|>|<|==|!=).+\)$
But it matches stuff like >=!= and so forth. I did look through the stackoverflow questions and googled but couldn't find the right solution.
Clould you please help me with that?
Upvotes: 2
Views: 1640
Reputation: 163
A regex like ^\(\s*[a-zA-Z0-9_+\-\/* ]+\s*(>=|<=|>|<|==|!=)\s*[a-zA-Z0-9_+\-\/* ]+\s*\)$
should do the trick, right?
A Regex101 with it in action can be found here.
Upvotes: 1
Reputation: 626758
If you are also planning to also capture strings like (myName == "Денис")
, you need to use the following regex:
^\((?>(?![<>=]=|!=|[<>]).)*?(?:[<>=]=|!=|[<>])(?>(?![<>=]=|!=|[<>]).)*?\)$
See demo on Regexstorm (supporting .NET regex flavor, unlike regex101.com)
It is much faster than Karthik Manchala's suggestion as per testing results at http://regexhero.net, due to the use of atomic grouping ((?> ... )
), character classes ([<>=]
), and and lazy matching (*?
). Also, in case a space is missing before or after ==
operator, my regex will still capture the expression.
With (?m)^\((?>(?![<>=]=|!=|[<>]).)*?(?:[<>=]=|!=|[<>])(?>(?![<>=]=|!=|[<>]).)*?\)$
my regex yields 15,783 iterations per second, and Karthik's
(?m)^\(((?!(>=|<=|>|<|==|!=)).)+\s+(>=|<=|>|<|==|!=)\s+((?!(>=|<=|>|<|==|!=)).)+\)$
yields 9,204 iterations per second speed.
Upvotes: 2
Reputation: 13640
You can use the following :
^\(((?!(>=|<=|>|<|==|!=)).)+\s+(>=|<=|>|<|==|!=)\s+((?!(>=|<=|>|<|==|!=)).)+\)$
Explanation:
((?!(>=|<=|>|<|==|!=)).)+
any character other than (>=|<=|>|<|==|!=)
\s+(>=|<=|>|<|==|!=)\s+
one of the operators followed by((?!(>=|<=|>|<|==|!=)).)+
any character other than (>=|<=|>|<|==|!=)
Upvotes: 1