正则表达式:仅当文本句子数大于1时删除以指定词开头的末尾句
正则修正方案
你需要调整正则的匹配逻辑,核心要满足两个前置校验:
- 必须存在至少1个前置句子(即匹配位置前有句子结束符+空格)
- 末尾句的开头必须直接是目标匹配串,不能有其他前缀字符
修正后的正则表达式如下:
"(?<=[.!?']\\s)[Jj]ack,? is.*?$"
正则逻辑说明
(?<=[.!?']\\s):正向回顾后发断言,要求匹配位置的前面必须是句子结束符(.?!'任意一个)加空格,确保文本至少有2个句子,过滤掉单句场景[Jj]ack,? is:匹配大小写开头的Jack,可选后接逗号,再跟is,严格校验句子开头的匹配规则.*?$:非贪婪匹配到文本末尾,覆盖整个末尾句子
调用代码
map_chr(test_strings, ~str_replace(.x, "(?<=[.!?']\\s)[Jj]ack,? is.*?$", "[TRIM]"))
修正后输出结果
[1] "Jack is the tallest person." [2] "and Jack is the one who said, let there be fries." [3] "There are mirrors. And Jack is there to be suave." [4] "There are dogs. And jack is there to pat them. Very cool." [5] "Jack is your lumberjack. [TRIM]" [6] "Whereas Jack is, for the whole summer, sound asleep. Zzzz" [7] "'Jack is so cool!' Jack is cool. [TRIM]"
所有测试用例均符合预期要求。
内容的提问来源于stack exchange,提问作者fluent
相关产品推荐
相关产品推荐

