r - 替换字符串中的第二个标点符号?
问题描述
有许多带有模式的字符串:
A B C D
我只需要将第二个“/”更改为其他内容(例如,*)
所以 A/B/C/D --> A/B*C/D
gsub('(^[[:punct:]])([[:punct:]])', "*", string) #Didn't Work
gsub('[[:punct:]]{2}', "*", string) #Didn't work
解决方案
您可以使用
sub("([^[:punct:]]*[[:punct:]][^[:punct:]]*)[[:punct:]]", "\\1*", string)
查看正则表达式演示
该sub
函数将找到一个(第一次)出现的
([^[:punct:]]*[[:punct:]][^[:punct:]]*)
- 第 1 组(\1
指替换模式中的此值):除标点符号之外的 0+ 个字符,一个标点符号,然后是除标点符号之外的 0+ 个字符[[:punct:]]
- 标点符号。
或者,您可以尝试类似的 PCRE 正则表达式
sub("\\P{P}*\\p{P}\\P{P}*\\K\\p{P}", "*", string, perl=TRUE)
请参阅此正则表达式演示。
但是,\p{P}
不匹配 what [[:punct:]]
does,所以要小心。或全部替换\p{P}
为[\p{P}\p{S}]
和全部\P{P}
替换为[^\p{P}\p{S}]
。
推荐阅读
- c - 第二次 calloc 问题 - 在 C 上
- javascript - 快速排序问题 - 没有得到正确的结果
- docker - Cloud Build,maven 包,没有目标文件夹
- php - 尝试使用 With 时按数据透视表排序数据
- python - Python 用 selenium 切换浏览器焦点
- javascript - 是否可以测量溢出滚动的距离?
- azure-devops - 在 Azure DevOps 构建管道中发送电子邮件通知的最佳方式?不想使用“通知模块”
- python - Jupyter Notebook 导入问题
- c# - 单击带有在运行时创建的控件的按钮更改文本框的文本
- api - 如何清理我的 json 响应以使其更清洁