Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何将正则表达式限制为较小的捕获_Ruby_Regex - Fatal编程技术网

Ruby 如何将正则表达式限制为较小的捕获

Ruby 如何将正则表达式限制为较小的捕获,ruby,regex,Ruby,Regex,以下是我的文字: "A popular resource for the Christian community in the Asheville area." "I love the acting community in the Orange County area." 我想捕捉“阿什维尔”和“奥兰治县”。如何开始从最近的“区域”捕获到“区域” 这是我的正则表达式: /the (.+?) area/ 它们捕捉到: "Christian community in the Asheville

以下是我的文字:

"A popular resource for the Christian community in the Asheville area."
"I love the acting community in the Orange County area."
我想捕捉
“阿什维尔”
“奥兰治县”
。如何开始从最近的
“区域”
捕获到
“区域”

这是我的正则表达式:

/the (.+?) area/
它们捕捉到:

"Christian community in the Asheville"
"acting community in the Orange County"
使用
(?:(?!the)。+?

看。它几乎与([^t]*(?:t(?!he)[^t]*)*?)区域相同,但因为它是展开模式

(?:(?!The)。+?
匹配任何不启动
字符序列的1+字符(尽可能少)

为了更安全,请添加单词边界以仅匹配整个单词:

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

s = 'I love the acting community in the Orange County area.'
puts s[/the ((?:(?!the).)+?) area/,1]
# => Orange County
注意:如果您希望匹配跨越多行,请不要忘记添加
/m
修饰符:

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

使用温和贪婪的解决方案,以便匹配的文本不包含另一个
the
。这样,它将始终匹配最后一个

/the (?:(?!the).)+? area/
  • (?:(?!the)。+?
    表示一个匹配任何字符的点,除了包含文本
    的字符外。这是使用负前瞻
    (?!the)
    提到的,它告诉它与文本
    the
    不匹配。因此,它确保匹配从不包含文本
    the
  • 通过使用捕获组仅提取
    区域
    区域
    之间的文本,可以进一步增强这一点。另一种方法是将
区域
设置为“向后看”和“向前看”,尽管这比捕获组要慢一点


阅读更多信息。

(?这是否有效?
)+?区域/
/\b([A-Z][A-Z]+\s?+\b)(?=area)/
可能很好。有趣的问题。我找不到使用字符串和可枚举方法的满意解决方案。
/the (?:(?!the).)+? area/
(?<=in the)(.*)(?=area)