【问题标题】:Matching series of Ampersands in R?R中匹配的&符号系列?
【发布时间】:2018-10-23 12:30:11
【问题描述】:

我无法解决以下问题。请求大家在这方面帮助我。

我的数据中有一系列 &

我的尝试和例子:

string1 <- "This aa should be replaced: but this aaa shouldn't"
string2 <- "This && should be replaced: but this &&& shouldn't"

gsub("aa", "XXX", string1)       #1.
gsub("\\baa\\b", "XXX", string1) #2.

gsub("&&", "XXX", string2)       #3.
gsub("\\b&&\\b", "XXX", string2) #4.

上面,如果我想匹配string1中的'aa',我可以有两种方法,

在方法 1(表示为:#1)中,我可以简单地传递 'aa' 但这也会部分匹配 'aaa',这是我不想要的,我希望我的正则表达式完全匹配成对的 'a' ,在我的情况下是'aa'。

为了解决这个问题,我使用了正则表达式(#2),在这种情况下它工作正常。

现在,在 string2 中,我预计会有类似的行为,我想要匹配不匹配的一对 '&&' 而不是匹配一对 'a'。

(#3) 尝试有效,但这不是我想要的结果,因为它也部分匹配 '&&&',

(#4) 尝试由于某种原因不起作用,它没有替换字符串。

我的问题是:

1) Why pair of ampersands are not working with boundary conditions ?

2) What is the way around to solve this problem ?

我真的很难过,因此浪费了我一整天,真的感觉很糟糕,尝试在谷歌上找到解决方案,但尚未成功。

如果有人知道,如果它在那里,请将我重定向到一个帖子。或者如果有人发现它是重复的,请告诉我,我会删除它。

感谢您的帮助和阅读问题。

编辑:我的单词边界现在是空格。

输出

> gsub("aa", "XXX", string1)
[1] "This XXX should be replaced: but this XXXa shouldn't"
> gsub("\\baa\\b", "XXX", string1)
[1] "This XXX should be replaced: but this aaa shouldn't"
> 
> gsub("&&", "XXX", string2)
[1] "This XXX should be replaced: but this XXX& shouldn't"
> gsub("\\b&&\\b", "XXX", string2)
[1] "This && should be replaced: but this &&& shouldn't"
> 

注意:我也检查了 perl=TRUE,但它不起作用。

【问题讨论】:

  • 请定义您的“单词边界”。那是空格和字符串的开始/结束吗? \b 匹配字符串的开始/结束与单词 char 之间的位置,或单词与非单词 char 之间的位置。
  • 然后使用gsub("(?&lt;!\\S)&amp;&amp;(?!\\S)", "XXX", string2, perl=TRUE)。您误解了 \b 的作用以及正则表达式中的“单词”是什么。

标签: r regex gsub


【解决方案1】:

\b word boundary 表示:

有资格作为单词边界的三个不同位置:

  • 在字符串的第一个字符之前,如果第一个字符是 单词字符。
  • 在字符串的最后一个字符之后,如果最后一个 字符是一个单词字符。
  • 在字符串中的两个字符之间, 其中一个是单词字符,另一个不是单词字符。

"\\b&amp;&amp;\\b" 模式与 &amp;&amp; 匹配时,它包含单词字符、字母、数字或 _ 字符。

要匹配空白边界,您可以使用

gsub("(?<!\\S)&&(?!\\S)", "XXX", string2, perl=TRUE)

模式匹配

  • (?&lt;!\\S) - 一个不紧跟在非空白字符前面的位置(即,必须在当前位置的左侧紧邻字符串或空白字符的开头)
  • &amp;&amp; - 文字子字符串
  • (?!\\S) - 一个不紧跟非空白字符的位置(即,当前位置右侧必须有字符串结尾或空白字符)。

【讨论】:

  • 等效地,您大概可以使用 `"\\B&&\\B" 来匹配 空白边界 而不是环视?
  • @MokeEire 这不是等价的,\B&amp;&amp;\B 匹配两个与符号,当它们用非单词字符(字母、数字和下划线以外的字符)或字符串的开头/结尾括起来时。
  • 空白字符包含在非单词字符中,对吗?
  • @MokeEire 是的,空格是非单词字符,因为它们不是字母、数字或_。空白边界是自定义边界,不如(非)单词边界通用。
  • 啊,所以和号也算作非单词边界,因此在原始帖子中产生相同的“XXX&”?
【解决方案2】:

更具体,但您可以像这样使用两步函数

replace2steps <- function(mystring, toreplace,replacement, toexclude, intermediate) {
  intermstring <- gsub(toexclude,  intermediate,string2)
  result <-  gsub(toreplace,  replacement, intermstring)
  result <-  gsub(intermediate,  toexclude, result)
  return(result)
}
replace2steps(string2, "&&", "XX", "&&&", "%%%")
[1] "This XX should be replaced: but this &&& shouldn't"

【讨论】:

    猜你喜欢
    • 2013-05-29
    • 2019-01-27
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多