gpt4 book ai didi

regex - 如何使用 R 的正则表达式用大括号替换方括号?

转载 作者:行者123 更新时间:2023-12-01 07:25:36 24 4
gpt4 key购买 nike

由于 pandoc-citeproc 和 latex 之间的转换,我想替换它

[@Fotheringham1981]

有了这个

\cite{Fotheringham1981}.

下面的可重现示例说明了单独处理每个括号的问题。

x <- c("[@Fotheringham1981]", "df[1,2]")
x1 <- gsub("\\[@", "\\\\cite{", x)
x2 <- gsub("\\]", "\\}", x1)

x2[1] # good
## [1] "\\cite{Fotheringham1981}"

x2[2] # bad
## [1] "df[1,2}"

看到一个类似的问题solved对于 C#,但不使用 R 的 perly regex - 有什么想法吗?

编辑:

它应该能够处理长文档,例如

old_rmd <- "$p = \alpha e^{\beta d}$ [@Wilson1971] and $p = \alpha d^{\beta}$
[@Fotheringham1981]."
new_rmd1 <- gsub("\\[@([^\\]]*)\\]", "\\\\cite{\\1}", old_rmd, perl = T)
new_rmd2 <- gsub("\\[@([^]]*)]", "\\\\cite{\\1}", old_rmd)

new_rmd1
## "$p = \alpha e^{\beta d}$ \\cite{Wilson1971} and $p = \alpha d^{\beta}$\n \\cite{Fotheringham1981}."

new_rmd2
## [1] "$p = \alpha e^{\beta d}$ \\cite{Wilson1971} and $p = \alpha d^{\beta}$\n\\cite{Fotheringham1981}."

最佳答案

你可以使用

gsub("\\[@([^]]*)]", "\\\\cite{\\1}", x)

参见 IDEONE demo

正则表达式分解:

  • \\[@ - 文字 [@ 符号序列
  • ([^]]*) - 匹配 0 次或多次出现的任何符号但 ] 的捕获组 1(请注意,如果 ]出现在字符类的开头,不需要转义)
  • ] - 文字 ] 符号

你不需要对这个使用 perl=T 因为字符类中的 ] 不会被转义。否则,将需要使用该选项。

另外,我认为我们应该只逃避必须逃避的东西。如果有办法避免backslash hell , 我们应该。因此,您甚至可以使用

gsub("[[]@([^]]*)]", "\\\\cite{\\1}", x)

这里是 another demo

为什么基于 TRE 的正则表达式比 PCRE 的效果更好:

在 R 2.10.0 及更高版本中,默认的正则表达式引擎是 Ville Laurikari 的 TRE 引擎的修改版本 [source] . library's author states用于匹配的时间随着输入文本长度的增加而线性增长,而内存需求几乎保持不变(数十 KB)。 TRE 也是 said在所用正则表达式匹配算法的长度中使用可预测和适度的内存消耗和二次最坏情况时间。这就是为什么在处理较大的文档时最好依赖 TRE 而不是 PCRE 正则表达式。

关于regex - 如何使用 R 的正则表达式用大括号替换方括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33608060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com