gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:59:32 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com