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

我只是一个虾纸丫 提交于 2019-12-07 06:29:59

问题


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?


回答1:


The comma appears because the capturing group contains it.

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

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



回答2:


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.



来源:https://stackoverflow.com/questions/17814421/java-regex-with-a-positive-look-behind-of-a-negative-look-ahead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!