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?

4
  • [!=<>] can represent only one character. Read about quantifiers (especially about greedy and reluctant). Commented Oct 20, 2014 at 20:14
  • Reply to pshemo: sorry it was my typo when typing the question. Now it is corrected Commented Oct 20, 2014 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 !=<>). Commented Oct 20, 2014 at 20:24
  • BTW, instead of Reply to pshemo use @pshemo :) this way I will be notified about your comment. Commented Oct 20, 2014 at 20:25

3 Answers 3

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 :

[^!=<>]+([!=<>]+)[^!=<>]+
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

2 Comments

Thank you, but this actually doesn't work. .+ still eats up !
No, it's the greediness of the leading .+ that's causing the problem, as explained in another answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.