【发布时间】:2021-11-02 10:35:56
【问题描述】:
我正在使用 R 阅读 PDF 文件。我想以这样一种方式转换给定的文本,即每当检测到多个空格时,我想用某个值替换它们(例如“_”)。我遇到了可以使用 "\\s+" (Merge Multiple spaces to single space; remove trailing/leading spaces) 替换所有 1 或更多空格的问题,但这对我不起作用。我有一个看起来像这样的字符串;
"[1]This is the first address This is the second one
[2]This is the third one
[3]This is the fourth one This is the fifth"
当我应用我找到的答案时;用单个空格替换 1 或更多的所有空格,我将无法再识别单独的地址,因为它看起来像这样;
gsub("\\s+", " ", str_trim(PDF))
"[1]This is the first address This is the second one
[2]This is the third one
[3]This is the fourth one This is the fifth"
所以我要找的是这样的东西
"[1]This is the first address_This is the second one
[2]This is the third one_
[3]This is the fourth one_This is the fifth"
但是,如果我重写示例中使用的代码,我会得到以下结果
gsub("\\s+", "_", str_trim(PDF))
"[1]This_is_the_first_address_This_is_the_second_one
[2]This_is_the_third_one_
[3]This_is_the_fourth_one_This_is_the_fifth"
有人知道解决方法吗?任何帮助将不胜感激。
【问题讨论】:
-
您可以使用
"\\s{2,}"或"\\s\\s+"