2016-02-13 66 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,所以(?<!\/)是沒有意義的