r - 在匹配之前找到两个单词
问题描述
我正在尝试使用正则表达式拆分字符串。我的正则表达式代码应该匹配冒号前的两个单词,最终目标是拆分如下内容:
"Joe Biden: We need to reform healthcare. It is important. Bernie Sanders: I agree. It is important."
变成这样的字符串向量:
"Joe Biden" "We need to reform healthcare. It is important." "Bernie Sanders" "I agree. It is important"
我得到的最接近的是:
foo <- strsplit(my_string, split="(\\S+)\\s*(\\S+)\\s*:",perl=TRUE)
但结果删除了正则表达式匹配。我尝试像这样使用lookbehind:
foo <- strsplit(my_string, split="(?<=.)(?=(\\S+)\\s*(\\S+)\\s*:)",perl=TRUE)
但它会抛出一个错误:
PCRE pattern compilation error
'lookbehind assertion is not fixed length'
at ')'
是否有替代正则表达式代码来完成此操作,或者我应该使用其他功能?
解决方案
这分裂了由 or 运算符分隔的两件事|
。1) 一个空格,后跟两个单词,由一个空格分隔,然后是一个冒号;2) 一个冒号,后跟一个空格。
my_string <- "Joe Biden: We need to reform healthcare. It is important. Bernie Sanders: I agree. It is important."
strsplit(my_string, split="( (?=\\w+ \\w+:)|: )",perl=TRUE)
[[1]]
[1] "Joe Biden" "We need to reform healthcare. It is important."
[3] "Bernie Sanders" "I agree. It is important."
如果说话者的名字只有一个词,你会在这里遇到的麻烦。这就是在我对您上一个问题的回答中寻找标点符号的目的。
推荐阅读
- vba - Excel VBA,最后一行的对象定义错误
- c++ - C++ 双指针数组到浮点数的转换
- java - Selenium 下载按钮表示通过 Java 浏览器下载的 zip 文件
- apache-spark - Pyspark 错误 - py4j.Py4JException:方法限制([class java.lang.String])不存在
- .htaccess - .htaccess 重写问题
- r - 字符总和
- python - 如何验证默认 ImageField 中的尺寸?
- c# - 在 ASP.NET Core Identity UI 中更改路由?
- php - PHP sql注入和函数中的自定义参数数量
- actions-on-google - 使用 Google Home 的 Google 登录检索电子邮件