我需要从这些字符串中提取名称(例如:“ L。Odem”或“ A. Bargani”)
Technical foul by L. Odom
Offensive foul by A. Bargnani (drawn by D. Granger)
Flagrant foul type 1 by B. Miller (drawn by J. Smith)
Flagrant foul type 1 by A. Croshere
Flagrant foul type 2 by M. Olowokandi
Away from play foul by R. Rogers
Offensive foul by T. MacCulloch
Personal foul by D. George
这是我尝试过的:
"(?<=foul by ).*"
这在大多数情况下都有效,但被“犯规”和“ by”之间具有“类型1”或“类型2”的明显犯规或以括号信息结尾且始终以“(绘制者
我觉得我已经接近了,但是可以使用一些帮助来解决这些问题。
非常感谢!
答案 0 :(得分:1)
您可以向后方添加第二种替代方法,并使用[^()]+
或[^()]*[^()\s]
将名称与第一个(
匹配:
(?<=foul by |foul type [12] by )[^()]*[^()\s]
请参见regex demo。在R中,使用
stringr::str_extract(x, "(?<=foul by |foul type [12] by )[^()]*[^()\\s]")
正则表达式详细信息
(?<=foul by |foul type [12] by )
-foul by
或foul type 1 by
或foul type 2 by
必须立即显示在当前位置的左侧[^()]*
-除(
和)
以外的0个或更多字符[^()\s]
-除空格(
和)
以外的字符。替代品:
stringr::str_match(x, "foul(?:\\s+type\\s+\\d+)?\\s+by\\s+([^()]*[^()\\s])")[,2]
This将找到名称,即使foul
,type
等之间的空格不一致,并且\d+
将匹配1
,{{ 1}}等(任意1个以上的数字)
12
This regex是带有PCRE正则表达式的基本R变体,它还允许不一致地使用空白和regmatches(x, regexpr("foul(?:\\s+type\\s+\\d+)?\\s+by\\s+\\K[^()]*[^()\\s]", x, perl=TRUE)
之后的任何1+数字。
详细信息
type
-一个foul
字符串foul
-可选序列
(?:\s+type\s+\d+)?
-\s+type\s+
内含1+空格type
-1个以上数字\d+
-\s+by\s+
内含1+空格by
-匹配重置运算符。