0

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?

user2829353
  • 63
  • 1
  • 6
  • `[!=<>]` can represent only one character. Read about [quantifiers](http://docs.oracle.com/javase/tutorial/essential/regex/quant.html) (especially about greedy and reluctant). – Pshemo Oct 20 '14 at 20:14
  • Reply to pshemo: sorry it was my typo when typing the question. Now it is corrected – user2829353 Oct 20 '14 at 20:20
  • Problem stays the same. First `.+` is greedy so it consumes characters which could be matched by `[!=<>]+`. You need to make it reluctant (or instead of `.` you can use negated character set to prevent matching `!=<>`). – Pshemo Oct 20 '14 at 20:24
  • BTW, instead of `Reply to pshemo` use `@pshemo` :) this way I will be notified about your comment. – Pshemo Oct 20 '14 at 20:25

3 Answers3

1

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 :

[^!=<>]+([!=<>]+)[^!=<>]+
JM Lord
  • 1,031
  • 1
  • 13
  • 29
1

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 ...

Community
  • 1
  • 1
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

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

Kristijan Iliev
  • 4,901
  • 10
  • 28
  • 47