简体   繁体   中英

Java regex with a positive look behind of a negative look ahead

I am trying to extract from this kind of string ou=persons,ou=(.*),dc=company,dc=org the last string immediately preceded by a coma not followed by (.*). In the last case, this should give dc=company,dc=org .

Looking on regex, this seems to be a positive look behind (preceded by) of a negative look ahead.

So I have achieve this regex: (?<=(,(?!.*\\Q(.*)\\E))).* , but it returns ,dc=company,dc=org with the coma. I want the same thing without the coma. What I am doing wrong?

The comma appears because the capturing group contains it.

You can make the outside capture group noncapturing with (?:)

(?<=(?:,(?!.*\Q(.*)\E))).*

It seems that I have solved my problem alone, removing the capturing group around the negative look ahead. It gives the following regex: (?<=,(?!.*\\Q(.*)\\E)).* .

It is linked with the behavior of capturing groups in look arounds as explained here: http://www.regular-expressions.info/lookaround.html in the part Lookaround Is Atomic .

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