2010-10-11 26 views
0

如何匹配任何地方都可能發生換行符的正則表達式?用換行符匹配正則表達式

例如,如果我想匹配「成千上萬只海龜蛋」,它應該匹配以下所有情況。 (甚至情況下,當換行符是裏面的話。)

Scientists have revealed that a mammoth effort to move *thousands of turtle eggs* from beaches around the Gulf of Mexico after the Deepwater Horizon oil spill may have saved almost 15,000 of the reptiles. 

Scientists have revealed that a mammoth effort to move *thousands 
of turtle eggs* from beaches around the Gulf of Mexico after the Deepwater Horizon oil spill may have saved almost 15,000 of the reptiles. 

Scientists have revealed that a mammoth effort to move *thousands of 
turtle eggs* from beaches around the Gulf of Mexico after the Deepwater Horizon oil spill may have saved almost 15,000 of the reptiles. 

Scientists have revealed that a mammoth effort to move *thousands of turtle 
eggs* from beaches around the Gulf of Mexico after the Deepwater Horizon oil spill may have saved almost 15,000 of the reptiles. 
+0

下一次,請向我們提供您正在使用的應用程序信息哪些regex庫,或者,因爲不同的庫/應用程序將使一個不同的正確答案。您也可以通過選擇多個適當的標籤來發出信號。 – Vantomex 2010-10-11 04:57:59

+1

@Vantomex正則表達式庫很重要嗎?我可以用通用答案做,而不是綁定到任何圖書館/應用程序。 - 謝謝 – 2010-10-13 01:44:02

+0

不是每個正則表達式lib都支持佔有量詞,原子分組等,它們可以用來優化庫的正則表達式解析速度。而且,他們有很多規則差異來實現正則表達式庫之間的相同結果。 – Vantomex 2010-10-13 01:53:51

回答

3
/thousands\s+of\s+turtle\s+eggs/ 

或此版本,以確保數千雞蛋不是一個單詞的一部分(如... eggsbath

/\bthousands\s+of\s+turtle\s+eggs\b/ 
+0

那些在單詞內可能出現換行的情況呢? – 2010-10-13 01:46:26

+0

只需在字母之間加上這種可能性:'/ \ bt [\ r \ n] * h [\ r \ n] * o [\ r \ n] * ...' – 2010-10-13 09:09:49

+0

好的......正在考慮是否有其他解決方案。 :) – 2010-10-15 09:45:34

0

您可以使用標誌「s」來匹配所有換行符。

如果使用正則表達式「/reptiles..*?sc/gis」它將匹配「reptiles.sc」

你可以試試這個link

這是一個在線的正則表達式編輯

0

使用's'開關。然後^ $成爲整個字符串的開始和結束,換行符被認爲是空白。所以只要你用\ s來匹配單詞之間的差距。 如:

#thousands \特種部隊\ sturtle \ seggs#SI

+0

對不起,但你走了。換行符總是被認爲是空白的,'\ s'總是匹配它們。 's'開關所做的是允許** dot **('.')匹配換行符,這在默認情況下不會執行。這是最初(不幸的)稱爲*單行*模式,但現在更常稱爲* dot-matches-all *或* DOTALL *模式。 's'開關對錨點('^'和'$')沒有影響。請參閱本教程的「Dot」和「Anchors」部分以獲取詳細信息:http://www.regular-expressions.info/tutorial.html – 2010-10-11 04:59:39

+0

謝謝。我不知道,我只是認爲這是我提到它的方式。我會研究它。 :) – Karthick 2010-10-11 07:37:43