繁体   English   中英

正则表达式匹配 R 中的杂散逗号

[英]Regular expression to match stray commas in R

我正在使用 R 中的 html 文本数据。 我拥有的数据片段如下所示:

text <- "<<p channel=\"test.com\" class=\"wordpress\">  ,  , LONDON — British 
supporters of the Black Lives Matter movement stormed the runway of London 
City Airport Tuesday, forcing a halt to flights in one of the boldest acts of 
protest by the group as it spreads beyond U.S. borders. ,  , ,"

我想删除杂散的逗号,但保留按预期出现的逗号(即,周二机场,强制...)。 杂散逗号通常在它们之间出现空格(有时一个,有时更多)。

我似乎一次只能删掉几个逗号:

gsub(",  +", "", text)

感谢您的建议

您可以使用

gsub(",(?:\\s+,)+", ",", text)

请参阅R 演示

详情

  • , - 逗号
  • (?:\\s+,)+ - 出现一个或多个空格字符,然后是逗号。

如果逗号之间不能有空格,请使用\s*而不是\s+

gsub(",(?:\\s*,)+", ",", text)

要同时删除逗号前的所有空格,请在开头添加\s*

gsub("\\s*,(?:\\s*,)+", ",", text)

并且要删除字符串开头和结尾的所有逗号,并“缩小”其中的逗号,您可以使用

gsub("^\\s*,(?:\\s*,)+\\s*|\\s*,(?:\\s*,)+\\s*$|\\s*(,)(?:\\s*,)+", "\\1", text)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM