R中的正则表达式:匹配字符序列之前的字符串 [英] Regex in R: matching the string before a sequence of characters
本文介绍了R中的正则表达式:匹配字符序列之前的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想提取某个单词之前的字符串的一部分.例如.我想在,没用"之前得到一切.
I want to extract a part of the string that comes before a certain word. E.g. I want to get everything before ", useless".
a <- "Experiment A, useless (03/25)"
b <- grep('^[^useless]+', a, perl=T)
regmatches(a,b)
这应该返回实验 A".
This should return "Experiment A".
然而,这行不通.R 给出子字符串中的错误(x[ind],所以,eo):无效的子字符串参数".
However, this doesn't work. R gives "Error in substring(x[ind], so, eo) : invalid substring arguments".
推荐答案
我们可以使用 sub
来匹配 ,
后跟零个或多个空格 (\\s*
) 后跟 'useless' 和其他字符 (.*
) 并将其替换为空白 (""
)
We can use sub
to match the ,
followed by zero or more spaces (\\s*
) followed by 'useless' and other characters that follow (.*
) and replace it with blank (""
)
sub(",\\s*useless\\b.*", "", a)
#[1] "Experiment A"
这篇关于R中的正则表达式:匹配字符序列之前的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文