【发布时间】:2013-04-11 00:04:42
【问题描述】:
我有正则表达式需要用\" 替换所有反斜杠\\,除非\\ 在两个美元符号$\\bar{x}$ 之间。我不知道如何在正则表达式中替换所有这些,除非它介于这两个字符之间。
这是一个字符串和一个gsub,即使在双倍美元内也能摆脱所有\\
x <- c("I like \\the big\\ red \\dog\\ $\\hat + \\bar$, here it is $\\bar{x}$",
"I have $50 to \\spend\\", "$\\frac{4}{5}$ is nice", "$\\30\\ is nice too")
gsub("\\\\", "\"", x)
## > gsub("\\\\", "\"", x)
## [1] "I like \"the big\" red \"dog\" $\"hat + \"bar$, here it is $\"bar{x}$"
## [2] "I have $50 to \"spend\""
## [3] "$\"frac{4}{5}$ is nice"
## [4] "$\"30\" is nice too"
我追求的是:
## [1] "I like \"the big\" red \"dog\" $\\hat + \\bar$, here it is $\\bar{x}$"
## [2] "I have $50 to \"spend\""
## [3] "$\\frac{4}{5}$ is nice"
## [4] "$\"30\" is nice too"
【问题讨论】:
-
我不认为正则表达式是解决这个问题的正确工具..您可能应该拆分并加入
$ -
@ExplosionPills 说了什么。这种语言充其量是上下文无关的,我很确定它是上下文相关的。最大的问题是像
"I have $50 to \\spend\\. My sister has $40."这样的东西有什么合适的? -
@FrankieTheKneeMan 这是一个我愿意处理的机会。预期目的是获取学术引用。这可能包括数学(而 $$ 是数学的标记方法)。我很少会遇到这样的美元符号的两种用法。
-
@Explosion Pills 我愿意接受我一直在寻找最有效的其他方法。我认为您可能可以像我一样使用
gsub,然后查找出现$$和"\\$.+?\\$"但无法连接最后一个点的情况。 -
我不是 R 天才,但您应该使用 stat.ethz.ch/R-manual/R-patched/library/base/html/strsplit.html 之类的东西来拆分
"$"上的字符串,然后在每个其他结果片段上运行您现有的 gsub。 (0、2、4 等...)无论如何,您可能还想在最后一块上运行它。然后您应该使用stat.ethz.ch/R-manual/R-patched/library/base/html/paste.html 将它们重新组合在一起。