regex 如何从字符串中删除带编号的换行符?

m4pnthwp  于 2022-12-05  发布在  其他
关注(0)|答案(2)|浏览(231)

我在清理一些文本数据时遇到了一个与删除换行符文本相关的问题。对于这些数据,文本中不仅有\n字符串,还有\n\n字符串,以及编号的换行符,例如:\n2\n\n2。后者是我的问题。如何使用regex删除它?
我在R中工作。下面是一些示例文本和我目前使用的内容:

#string
string <- "There is a square in the apartment. \n\n4Great laughs, which I hear from the other room. 4 laughs. Several. 9 times ten.\n2"
#code attempt
gsub("[\r\\n0-9]", '', string)

这个正则表达式代码的问题是它删除了数字并与字母n匹配。
我希望得到以下输出:

"There is a square in the apartment. Great laughs, which I hear from the other room. 4 laughs. Several. 9 times ten."

我使用regexr作为参考。

lrpiutwd

lrpiutwd1#

要从字符串中删除换行符和数字,可以使用以下正则表达式:

gsub("\\n[\\n]?[0-9]?", '', string)

这将删除任何\n后面跟有一个可选\n字符和一个数字的\n字符。请注意,正则表达式中的反斜杠需要在字符串中转义,因此我们在正则表达式中为每个反斜杠使用两个反斜杠。
下面是在R中使用这个正则表达式的一个例子:

#string
string <- "There is a square in the apartment. \n\n4Great laughs, which I hear from the other room. 4 laughs. Several. 9 times ten.\n2"
#code attempt
gsub("\\n[\\n]?[0-9]?", '', string)

这将输出以下字符串:

"There is a square in the apartment. Great laughs, which I hear from the other room. 4 laughs. Several. 9 times ten."
d4so4syb

d4so4syb2#

将模式写为[\r\\n0-9]匹配回车符、字符\n之一或数字0-9
您可以编写匹配一个或多个回车或换行符的模式,后跟可选数字:

[\r\n]+[0-9]*

示例:

string <- "There is a square in the apartment. \n\n4Great laughs, which I hear from the other room. 4 laughs. Several. 9 times ten.\n2"
gsub("[\r\n]+[0-9]*", '', string)

输出量

[1] "There is a square in the apartment. Great laughs, which I hear from the other room. 4 laughs. Several. 9 times ten."

观看R演示。

相关问题