如何在 stringr 中使用正则表达式执行 find/replace

How to do a find/replace with a regular expession in stringr

给定一个字符串 'run- ning' 我想用 'nn' 替换 'n- n' 以获得 'running'.

使用 stringr 包我试过这个:

str_replace_all(s, "[:alpha:]\-([ ])+[:alpha:]", "[:alpha:][:alpha:]")

但它似乎不是那样工作的。我想需要使用变量,但我可以弄清楚具体如何。

我试过这个:

str_replace_all(s, "[:alpha:]\-([ ])+[:alpha:]", "\0\1")

但这也没有给出想要的结果。

有什么想法吗?

您可以使用

stringr::str_replace_all(s, "(?<=\p{L})- +(?=\p{L})", "")
stringr::str_replace_all(s, "(\p{L})- +(\p{L})", "\1\2")

或者,匹配任何水平空白字符

stringr::str_replace_all(s, "(?<=\p{L})-\h+(?=\p{L})", "")
stringr::str_replace_all(s, "(\p{L})-\h+(\p{L})", "\1\2")

基本 R 等效值:

gsub("(?<=\p{L})-\h+(?=\p{L})", "", s, perl=TRUE)
gsub("(\p{L})-\h+(\p{L})", "\1\2", s, perl=TRUE)
gsub("([[:alpha:]])-\s+([[:alpha:]])", "\1\2", s)

regex demo

详情

  • (?<=\p{L}) - 与任何 Unicode 字母
  • 前面紧接的位置匹配的正后视
  • - + - 连字符后跟 1 个或多个空格(\h 匹配任何水平空格)
  • (?=\p{L}) - 匹配紧跟任何 Unicode 字母的位置的正向前瞻。
  • (\p{L}) - 匹配任何字母的捕获组。

使用捕获组的示例中替换模式中的 是对相应捕获组值的反向引用。