regex - 使用正则表达式在 LaTeX 表中查找(并替换)第 n 列

标签 regex r

我有一个字符串,它是一个 LaTeX 表。我试图找到第 n 个(假设是第三个)列并将所有内容包装在里面,比如 \emph{} 而不匹配分隔美元符号。

我正在寻找第一个 &...& ,它是第二列。然后找到下一个 &...&,它是第二个分组,而且绝非表格中的第三列。

我的虚拟示例有效但有点不同,因为它在两个 &...& 之间有文本。稍后我会处理一些小事 - 我需要使用后向和前向引用将 & 放在 \emph{} 调用之外。

xy <-  "This is &more or less& a match and here is &another one&.\nSecond line with &occurrance 1& and &occurrance 2&"
gsub("(&.*?&)|(.*?&)(.*)(&.*?&)", "\\1\\2\\3\\\\emph{\\4}", xy, perl = TRUE)
[1] "This is &more or less& a match and here is \\emph{&another one&}.\nSecond line with &occurrance 1& and \\emph{&occurrance 2&}"

当我用 LaTeX 表格将其提升到一个读取集时(砰!),它有点不同。两个 &...& 之间没有字符,这意味着一个 & 与两列相邻。考虑到这一点,我删除了 (.*)。无论我尝试什么,我都无法让它发挥作用。有什么建议吗?

library(xtable)
data(tli)
tli.table <- xtable(tli[1:5,])
x <- print.xtable(tli.table, print.results = FALSE, include.rownames = FALSE)

cat(x)
% latex table generated in R 2.15.1 by xtable 1.7-0 package
% Thu Jul 26 14:13:39 2012
\begin{table}[ht]
\begin{center}
\begin{tabular}{rlllr}
  \hline
grade & sex & disadvg & ethnicty & tlimth \\ 
  \hline
  6 & M & YES & HISPANIC &  43 \\ 
    7 & M & NO & BLACK &  88 \\ 
    5 & F & YES & HISPANIC &  34 \\ 
    3 & M & YES & HISPANIC &  65 \\ 
    8 & M & YES & WHITE &  75 \\ 
   \hline
\end{tabular}
\end{center}
\end{table}

gsub("(&.*?&)(&.*?&)", "\\1\\\\emph{\\2}", x, perl = TRUE)

最佳答案

假设第 1st 列是 n <- 1 (而不是 n <- 0 ),您应该用于替换第 n 列的正则表达式应该是:

(?m)^(?=[^&\n\r]*&)((?:[^&]*&){n-1})\\s*([^&]*?)\\s*(&|\\\\)
                                ↑
                                └ replace this n-1 with real number

然后替换字符串必须是 \\1\\\\emph{\\2}\\3 .

所以你的替换代码是:

input <- "% latex table generated in R 2.15.1 by xtable 1.7-0 package\n% Thu Jul 26 17:49:09 2012\n\\begin{table}[ht]\n\\begin{center}\n\\begin{tabular}{rlllr}\n  \\hline\ngrade & sex & disadvg & ethnicty & tlimth \\\\ \n  \\hline\n  6 & M & YES & HISPANIC &  43 \\\\ \n    7 & M & NO & BLACK &  88 \\\\ \n    5 & F & YES & HISPANIC &  34 \\\\ \n    3 & M & YES & HISPANIC &  65 \\\\ \n    8 & M & YES & WHITE &  75 \\\\ \n   \\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n"

n <- 1
regex <- paste(c('(?m)^(?=[^&\n\r]*&)((?:[^&]*&){', n-1, '})\\s*([^&]*?)\\s*(&|\\\\)'), collapse='')
cat(gsub(regex, "\\1\\\\emph{\\2}\\3", input, perl = TRUE))

关于regex - 使用正则表达式在 LaTeX 表中查找(并替换)第 n 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11669352/

相关文章:

python - 我该如何替换 python 中的正则表达式?

java - java中模式的字符串比较

r - 如何在 R 中使用 ggplot2 绘制类似的图?

r - 使用 magrittr 和 lapply 将列表中每个 df 中的列除以值列表

regex - grep 模式从文件中排除负数

c# regex 只获取字符串中的负数

c# - 将正则表达式转换为 htmlagilitypack

r - 当已知可能的输出时加速 `strsplit`

r - 在 R 中,有没有办法在同一台机器上的 R 的不同进程之间共享一个变量?

r - 如何按数据框或矩阵中的不同行进行子集化?