【问题标题】:Replace latex with r strings using gsub [duplicate]使用 gsub 用 r 字符串替换乳胶 [重复]
【发布时间】:2021-04-21 16:32:47
【问题描述】:

我想查找 tabular 实例并将其替换为 tabularx。我试过gsub,但它似乎让我进入了一个逃避痛苦的世界。在其他问题和答案之后,我找到了fixed=TRUE,这是我迄今为止最好的。下面的代码 sn-p 几乎可以工作, \B 无法识别。如果我将其转义两次,则会得到 \BEGIN 作为输出!

texText <- '\begin{tabular}{rl}\begin{tabular}{rll}'

texText <- gsub("\begin{tabular}{rl}", "\BEGIN{tabular}{rll}", texText, fixed=TRUE)

我使用 BEGIN 作为我的测试,看看发生了什么。这是在我解决括号 {rl} {ll} {rrl} 等中发生的问题之前。理想情况下,我正在寻找一个可以输出的正则表达式:

\begin{tabularx}{rX}\begin{tabularx}{rlX}

即最后一列被X替换。

【问题讨论】:

  • '\\B'\B 文本。您可以使用cat('\\B') 轻松查看。 要定义文字反斜杠,它必须加倍'\\'。顺便说一句,fixed=TRUE 触发固定、非正则表达式、搜索和替换。

标签: r string latex


【解决方案1】:

尝试使用正确的转义:

texText <- "\begin{tabular}{rl}\begin{tabular}{rll}"
output <- gsub("\begin\\{tabular\\}", "\begin{tabularx}", texText)
output

[1] "\begin{tabularx}{rl}\begin{tabularx}{rll}"

文字反斜杠需要两个反斜杠,并且像{} 这样的元字符也需要两个反斜杠。

【讨论】:

  • 抱歉错字,已修正。
  • 啊哈,太好了,谢谢。我的头现在已经停止了逃跑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多