2016-02-13 65 views
-2

当我使用:如何在正则表达式中反转正向lookbehind(?<=)?

String s = "http://google.com, /home/roroco/Dropbox/jvs/ro-idea/META-INF/plugin.xml" 
ArrayList<String> ms = s.findAll(/(?<=\/)\/\S+/) 
println(ms) 

输出是:

[/google.com,] 

当我更改为:

s.findAll(/(?<!\/)\/\S+/) 

输出是:

[//google.com,, /home/roroco/Dropbox/jvs/ro-idea/META-INF/plugin.xml] 

在我understandi ng,/(?<!\/)\/\S+/输出应该与/(?<=\b)\/\S+/输出相同,但事实上并非如此。为什么?

+0

你有什么需要得到什么? '/(?<!\ /)\/\ S + /'!='/(?<= \ b)\/\ S + /'因为'\ b'是一个字边界, /'。 '(?<!\ /)'如果在'/'之前有'/',那么匹配失败。 –

回答

1

关于你的问题。结果不能相同。看:

(?<!/)/\S+意味着find the place where "/" standing before "/" and give me this "/" with all non-whitespace character after it。只有一个地方。

结果将是:/google.com,

。在你的字符串中没有其他地方"/"字符前"/"


(?<=\b)\/\S+意味着find the place where word boundary standing before "/" and give me this "/" and all non-whitespace character after it代表。

结果将是:/roroco/Dropbox/jvs/ro-idea/META-INF/plugin.xml

在字"home"和字符"/"的这种情况下,信"e"本人也将被视为单词边界。


就脱颖而出参考:

(?<=)是正向后看。它会检查字符串中当前位置之前的内容。例如:

(?<=foo)bar意味着select 'bar', if 'foo' standing before

(?<!)为负向后看。它检查,立即不在之前的当前位置。例如:

(?<!foo)bar装置select 'bar', if 'foo' does NOT standing before

\b意味着字边界。它匹配一方是单词字符而另一方不是单词的位置。例如:

(?<=\b)bar意味着select 'bar', if word boundary standing before"foo bar"串 搜索将返回"bar"因为词与词之间的空间。但"foobar"将不会返回任何内容,因为最后一个字符串中的单词之间没有空格,所以在"bar"之前没有字边界。

+0

[regex101.com](http://regex101.com)不足以解释正则表达式的含义吗?你的回答根本没有帮助。至少因为我们不知道OP的需求。 –

+0

@WiktorStribiżew我很抱歉,我的回答对你没有帮助。我回答说,因为我理解这个问题。 –

+0

不,@WiktorStribiżew是正确的,这个答案只是一般信息的集合;它没有解决实际问题。 –

0

\/\S+将匹配//google.com,所以(?<!\/)是没有意义的