首页 > 解决方案 > 替换字符串中的第二个标点符号?

问题描述

有许多带有模式的字符串:

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

标签: rregex

解决方案


您可以使用

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}]


推荐阅读