regex - 从 R 中的字符串中删除指定的模式

标签 regex r text

我有一个类似下面的字符串

s <- "abc a%bc 1.2% 234 1.2 (1.4%)) %3ed"

我想删除所有带有 % 的“单词”。所以结果会是

"abc 234 1.2"

最佳答案

你可以使用

> gsub("^\\s+|\\s+$", "", (gsub("\\s+", " " ,gsub("\\s+\\S*%\\S*(?=\\s+|$)", " ",input, perl=TRUE))))
#[1] "abc 234 1.2"

代码分解

gsub("^\\s+|\\s+$", "", (gsub("\\s+", " " ,gsub("\\s+\\S*%\\S*(?=\\s+|$)", " ",input, perl=TRUE))))
                                           <--------------------------------------------------->
                                                     Remove strings with %
                        <------------------------------------------------------------------------>
                        Substitute extra spaces with single space from resultant string obtained from above
<-------------------------------------------------------------------------------------------------->
      Trim initial and final whitespaces from the string obtained from above

正则表达式分解

\\s+ #Match whitespaces
\\S* #Match all non whitespace character before % if its there
% #Match % literally
\\S* #Match all non whitespace character after % if its there
(?=\\s+|$) #Lookahead to check whether there is a space or end of string after matching word with %

关于regex - 从 R 中的字符串中删除指定的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37948440/

相关文章:

regex - Grep 正则表达式 : How to find multiple area codes in phone number?

r - 使用R的data.table用NA替换不可能的值

text - 在 AutoHotkey 中快速发送长文本

安卓锁屏

python - 直接以 NLTK 模式应用字符串

c# - 匹配 [0-9]-[0-9]-[0-9] 的模式,但不匹配 [0-9]-[0-9]

R:加速双循环

javascript - 如何在 JavaScript 中实现文本换行?

regex - 带有通配符和问号的 Apache Rewrite 问题

r - 如何使用 data.table 将表格应用于多个列?