Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.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
Regex scala:正则表达式,用于在某个短语之前和之后查找x个单词_Regex_Scala - Fatal编程技术网

Regex scala:正则表达式,用于在某个短语之前和之后查找x个单词

Regex scala:正则表达式,用于在某个短语之前和之后查找x个单词,regex,scala,Regex,Scala,我试图在一个自由文本中识别街角 我有一个街道列表,我正在寻找一个正则表达式,给出以下文本 the corner of Saint John and Mac Dowell. 或 会返回类似于 (Saint John) (Mac Dowell) 我在想类似的事情 .*((?:\w+\b+){5})and\b+((?:\w+\b+){5}).* 在“和”前面加五个词,后面加五个词。(我没有超过五个单词的街道名称) 但我甚至找不到一种方法来匹配一定数量的单词 如果我试着 scala> val

我试图在一个自由文本中识别街角

我有一个街道列表,我正在寻找一个正则表达式,给出以下文本

the corner of Saint John and Mac Dowell.

会返回类似于

(Saint John) (Mac Dowell)
我在想类似的事情

.*((?:\w+\b+){5})and\b+((?:\w+\b+){5}).*
在“和”前面加五个词,后面加五个词。(我没有超过五个单词的街道名称)

但我甚至找不到一种方法来匹配一定数量的单词

如果我试着

scala> val corner = """.*((?:\w+\b+){2}).*""".r
scala> val corner(c) = "word1 word2 word3"
一点也不匹配

(我不使用\s,因为我想将、;:.等作为分词符考虑在内)

--

多亏了m.buettner的回答,我可以更接近我想要实现的目标

现在我有:

val corner = """.*((?:\W+\w+){1,5})\W+and\W+((?:\w+\W+){1,5}).*""".r

val corner(a,b) = "the store located at Saint John street and Mac Dowell Avenue, is a great place"
a: String = " street"
b: String = "Mac Dowell Avenue, is a "

我唯一的问题是,我希望a位于“圣约翰街”,而不仅仅是“街道”。默认情况下,它不应该是急切的吗?

问题是
\b
不使用任何字符,它只检查当前位置是否在单词和非单词字符或字符串边界之间。但是您不必使用
\s
,您可以使用
\W
(表示任何非单词字符):

但为什么不简单地使用:

the corner of\W+(.*)\W+and\W+(.*)\W*

非常感谢你的回答,它真的帮助了我,现在我被前五个字难住了。我更新了问题。我不能只使用你给出的公式,因为文本不是那么固定的,我唯一能告诉我的是,可能会提到一个角的是短语的“和”部分。@opensas的问题是,
*
也是贪婪的,所以它会消耗掉所有东西,直到
John
,然后重复开始,这只能得到一个词。我将根据Scala是否支持向前看和向后看来更改我的问题?
.*?((?:\w+\W+){1,5})and((?:\W+\w+){1,5}).*
the corner of\W+(.*)\W+and\W+(.*)\W*