简体   繁体   English

Java正则表达式(分组)

[英]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. 例如,如果表达式是a!= 2,则group(1)是“ =”,而不是“!=”,这是我期望的。

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). 您也可以尝试不愿意或不愿意的版本(有关详细说明,请参见其他posr )。 In your example, it would be : 在您的示例中,它将是:

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

But this regex could match incorrect comparisons like a <!> b , or a =!><=! b 但是此正则表达式可以匹配不正确的比较,例如a <!> ba =!><=! b 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: !, =, <, > 放在方括号中的所有内容都将匹配一个字符,这意味着[!=<>]可以匹配: !, =, <, >

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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