[英]Regmatches in R not working
I am trying to add a column to a data set in R. The column should be the initials from a name column. 我正在尝试向R中的数据集添加一列。该列应该是name列的缩写。 I am trying to use
lapply
and passing in a function to get the initials - however, I can't get this regexp to work. 我正在尝试使用
lapply
并传入一个函数来获取缩写-但是,我无法使此正则表达式正常工作。
pattern <- "(\b[a-zA-Z])"
str<-"MICHAEL, JENSON F"
m <- regexpr(pattern,str,perl=TRUE)
regmatches(str,m)
Returns character(0) 返回字符(0)
How can I have R return a list of matches of a string? 如何让R返回字符串的匹配列表? I want regmatches to return MJ and F.
我想让regmatch返回MJ和F。
There are two problems: \\b
must be escaped and you should use gregexpr
instead of regexpr
because the latter returns only the first match. 有两个问题:
\\b
必须转义,并且应使用gregexpr
而不是regexpr
因为后者仅返回第一个匹配项。
pattern <- "(\\b[a-zA-Z])"
str<-"MICHAEL, JENSON F"
m <- gregexpr(pattern,str,perl=TRUE)
regmatches(str,m)[[1]]
# [1] "M" "J" "F"
只是想出了Stringr库。
str_match_all(str, "(\\b[a-zA-Z])[a-zA-Z]* ?")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.