简体   繁体   中英

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?

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 :

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

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 a =!><=! b ...

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: !, =, <, >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM