我正在尝试将长字符串按关键短语前后发生的几个因素进行分割。我能够在第一次出现时将其部分分割,但不能对每个分割。此外,以前没有任何与模式匹配有关的问题能够为我解答。
文本示例行:
"#1 Player A advances to third on a wild pitch. #2 Player B advances to second on an error."
部分解决方案:
gsub('((advances).*$)', '', "#1 Player A advances to third on a wild pitch. #2 Player B advances to second on an error.", ("[\\w]*) advances"))
返回:
"#1 Player A "
但是,我想:
[1] "#1 Player A advances to third" [2] "#2 Player B advances to second"
作为两个单独的输出字符串。
我不知道提取短语“ advances to ...”和玩家编号之间的文本的技术。
先感谢您!
如果我们假设有趣的部分始终以a开头,之后是#
一个单词advances to
,那么我们可以这样做:
s <- "#1 Player A advances to third on a wild pitch. #2 Player B advances to second on an error."
regmatches(s, gregexpr("#[[:alnum:] ]+ advances to \\w+", s))
# [[1]]
# [1] "#1 Player A advances to third" "#2 Player B advances to second"
(我更喜欢使用gregexpr
and的更为冗长的一个原因regmatches
是,当“ nothing”匹配时,它不会返回“ something”,与之不同gsub
的是除非精心设计了正则表达式。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句