user2829353
user2829353

Reputation: 63

Java regular expression(grouping)

I am try to write a regex to match conditional expressions, for example:

a!=2     1+2<4       f>=2+a

and I try to extract the operator. My current regex is ".+([!=<>]+).+"

But the problem is that the matcher is always trying to match the shortest string possible in the group.

For example, if the expression is a!=2, then group(1) is "=", not "!=" which is what I expect.

So how should I modify this regex to achieve my goal?

Upvotes: 0

Views: 71

Answers (3)

Serge Ballesta
Serge Ballesta

Reputation: 148880

You could also try the reluctant or non-greedy versions (see that other posr for extensive explain). In your example, it would be :

.+?([!=<>]+).+

But this regex could match incorrect comparisons like a <!> b, or a =!><=! b ...

Upvotes: 1

Kristijan Iliev
Kristijan Iliev

Reputation: 4987

Try this:

.+(!=|[=<>]+).+

your regex is matching a single ! because it is in []

Everything put in brackets will match a single char, which means [!=<>] can match: !, =, <, >

Upvotes: 0

JM Lord
JM Lord

Reputation: 1197

You want to match an operator surrounded by something that is not an operator.

An operator, in your definition : [!=<>]

Inversely, not an operator would be : [^!=<>]

Then try :

[^!=<>]+([!=<>]+)[^!=<>]+

Upvotes: 1

Related Questions