2017-05-30 62 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命令中键入的下一个单词。