2017-05-30 61 views
3

這裏是我的文字:如何限制正則表達式來捕獲小

"A popular resource for the Christian community in the Asheville area." 
"I love the acting community in the Orange County area." 

我想拍攝"Asheville""Orange County"。我怎樣才能從最接近的"the""area"

這裏是我的正則表達式:

/the (.+?) area/ 

他們捕捉:

"Christian community in the Asheville" 
"acting community in the Orange County" 
+0

這是否工作'/((?:(?!the)。)+?面積/'? [Demo](https://regex101.com/r/qWQ4aS/1/) – degant

+0

'/ \ b(([AZ] [az] + \ s?)+ \ b)(?= area)/'可能是好。 –

+0

有趣的問題。使用String和Enumerable方法找不到令人滿意的解決方案。 –

回答

2

使用(?:(?!the).)+?tempered greedy token

/the ((?:(?!the).)+?) area/ 

regex demo。它幾乎與/the ([^t]*(?:t(?!he)[^t]*)*?) area/相同,但the latter is a bit more efficient因爲它是展開模式。

(?:(?!the).)+?匹配任何1+字符(儘可能少),不會啓動the字符序列。

爲了使它更安全,添加單詞邊界僅全字匹配:

/\bthe ((?:(?!\bthe\b).)+?) area\b/ 

紅寶石演示:

s = 'I love the acting community in the Orange County area.' 
puts s[/the ((?:(?!the).)+?) area/,1] 
# => Orange County 

注意:如果你希望比賽在多個線路跨越,不忘了添加/m修改:

/the ((?:(?!the).)+?) area/m 
         ^
2

使用回火貪婪的解決方案,因此T匹配文本的帽子不包含另一個the。這樣,它會一直匹配最後the

/the (?:(?!the).)+? area/ 
  • (?:(?!the).)+?表示匹配任意字符,除了一個包含文本the回火貪婪點。這是使用負面預測(?!the),它告訴它不匹配文本the。因此它確保匹配永不包含文本the
  • 這可以通過使用捕獲組來提取thearea等之間的文本來進一步增強。另一種方法是將thearea作爲後視和前視,雖然會比捕獲組慢一點。

Regex101 Demo

Rubular Demo

瞭解更多關於tempered greedy solution and when to use it

2
(?<=in the)(.*)(?=area) 

(< =?):看後面命令 (?=):向前看命令,這將排除您在=符號後鍵入的字符串。在這種情況下,'在'和'區域'將被排除在結果之外。

(。)在這裏使用'貪婪',但您可以使用(。?)來匹配在look ahead命令中鍵入的下一個單詞。