R - 使用正则表达式查找/替换换行符

标签 r regex

我正在尝试使用正则表达式清理文件夹中的一堆 .txt 文件。我似乎无法让 R 找到换行符。

这是我正在使用的代码。它适用于字符替换,但不适用于换行符。

gsub_dir(dir = "folder_name", pattern = "\\n", replacement = "#")

我还尝试过\r 和各种其他排列。使用纯文本编辑器,我找到所有带有\n 的换行符。

最佳答案

您不能使用 xfun::gsub_dir 来做到这一点。

看看 source code :

  • 使用 read_utf8 读取文件,基本上执行 x = readLines(con,encoding = 'UTF-8', warn = FALSE),
  • 然后,gsub 被输入这些行,当所有替换完成后,
  • write_utf8 function将行...与 LF、换行符、符号连接起来。

为此,您需要使用一些自定义函数,这是“快速而肮脏”的函数,它将用 # 替换所有 LF 符号:

lbr_change_gsub_dir = function(newline = '\n', encoding = 'UTF-8', dir = '.', recursive = TRUE) {
 files = list.files(dir, full.names = TRUE, recursive = recursive)
 for (f in files) {
   x = readLines(f, encoding = encoding, warn = FALSE)
   cat(x, sep = newline, file = f)
 }
}

folder <- "C:\\MyFolder\\Here"
lbr_change_gsub_dir(newline="#", dir=folder)

如果您希望能够匹配多行模式,请粘贴使用换行折叠行并使用您喜欢的任何模式:

lbr_gsub_dir = function(pattern, replacement, perl = TRUE, newline = '\n', encoding = 'UTF-8', dir = '.', recursive = TRUE) {
 files = list.files(dir, full.names = TRUE, recursive = recursive)
 for (f in files) {
   x <- readLines(f, encoding = encoding, warn = FALSE)
   x <- paste(x, collapse = newline)
   x <- gsub(pattern, replacement, x, perl = perl)
   cat(x, file = f)
 }
}

folder <- "C:\\1"
lbr_gsub_dir("(?m)\\d+\\R(.+)", "\\1", dir = folder)

这将删除仅数字行后面的行。

关于R - 使用正则表达式查找/替换换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55284424/

相关文章:

r - 观星者汇总表中的可变组标题

删除 R Markdown 中的幻灯片编号

c# - 使用 Visual Studio 2013 正则表达式查找 - 如何使多个前缀无效

regex - ~/pattern/和 ~ "pattern"之间的区别?

Java:使用带有多个分隔符的 split 函数

R如何在nlslist中使用边界和 "port"算法?

r - 我如何在 R 中的基数系统上执行数学运算

r - 有没有办法到 `source()` 并在错误后继续?

javascript - 将其他语言的数字更改为英文数字的正则表达式

java - 如何使用 Pattern 和 Matcher 获取所有找到的组