Pergunta

I want to use negative look-ahead in java, but I can not apply it for only some portion of the text. It is used from the cursor until the end. Is it possible to do it somehow?

An Example: I have a string with indefinite 'ab's around it: ababJJJababab

I want that only the center portion without the 'ab's to be grouped (i.e JJJ). So here is my regular expression:

^(?:ab)*((?!.*ab.*).*)(?:ab)*$

The problem is that the negative lookahead goes beyond its container group and tries to avoid 'ab's until the end of the text (which would result in not finding any match at all). Please note that my actual issue is much more complex and I am not looking for a way around this particular example. Is there any way for assigning some sort of boundary for defining the scope for a lookahead in regex avoiding it to be applied to the rest of the text?

Thanks in advance ...

Foi útil?

Solução 2

In that particular case, you don't need a negative lookahead at all. You just need to make the middle quantifier non-greedy so it doesn't consume the trailing "ab"s:

^(?:ab)*(.*?)(?:ab)*$

Outras dicas

In this specific case, a minimal match should work. However, in the general case, you want something like this:

(?sx)
(?:abc) ( (?: (?!abc) .)* ) (?:abc)

I also don’t trust all your stars on the first and last parts. You realize your pattern matches the empty string, don’t you?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top