[英]Regexpr with lookaround in R
我试图在字符串(255; 0; 0)中获取bgcol的值 。
我没有设法弄清楚R中的前瞻,这对于此任务很有用,因此我不得不将regexpr+regmatches
与2个后续gsub
调用结合使用。
string <- "<params description=\"some desc\" bgcol=\"248;186;203\" col=\"0;200;0\"/>"
string <- "<params description=\"some desc\" bgcol=\"255;0;0\"/>"
bgcol = regmatches(string, regexpr('(bgcol=\"(.*)\")', string, perl=TRUE))
bgcol = gsub(pattern = "\"", replacement="", bgcol)
bgcol = gsub(pattern = "bgcol=", replacement="", bgcol)
as.integer(strsplit(bgcol, ";")[[1]])
[1] 255 0 0
如何简化/美化上面的正则表达式?
您可以使用此模式'.*bgcol=\\"(\\\\d*;\\\\d*;\\\\d*)\\"\\\\s?.*'
> bgcol <- gsub('.*bgcol=\"(\\d*;\\d*;\\d*)\"\\s?.*', "\\1", strings)
> lapply(strsplit(bgcol, ";"), as.integer)
[[1]]
[1] 255 0 0
[[2]]
[1] 248 186 203
您可以使用regmatches
/ regexec
:
string <- "<params description=\"some desc\" bgcol=\"255;0;0\"/>"
lapply(strsplit(regmatches(string, regexec('bgcol="([^"]*)"', string))[[1]][2], ";"), as.integer)
## => [[1]]
## [1] 255 0 0
bgcol="([^"]*)"
模式匹配bgcol="
,然后匹配并捕获除"
之外的任何0+字符到组1中( regexec
跟踪所有捕获的子字符串),然后匹配"
。
或带有regmatches
/ regexpr
的PCRE模式:
lapply(strsplit(regmatches(string, regexpr('bgcol="\\K[^"]*', string, perl=TRUE)), ";"), as.integer)
## => [[1]]
## [1] 255 0 0
观看在线R演示
bgcol="\\\\K[^"]*
模式匹配bgcol="
,然后在\\K
match reset运算符的帮助下将此文本从匹配中删除,只有与[^"]*
匹配的文本保留在比赛。
为了完整性,更stringr
解决方案:
> library(stringr)
> lapply(strsplit(str_extract(string, '(?<=bgcol=")[^"]*'), ";"), as.integer)
[[1]]
[1] 255 0 0
> lapply(strsplit(str_match(string, 'bgcol="([^"]*)"')[,2], ";"), as.integer)
[[1]]
[1] 255 0 0
请注意, str_extract
函数中的(?<=bgcol=")
仅在当前位置的左侧立即检查bgcol="
,因此它不是匹配项的一部分。
您可以使用read.table
read.table(text = gsub('.*bgcol.*?(\\d+;\\d+;\\d+).*', '\\1', string), sep=';')
V1 V2 V3
1 248 186 203
2 255 0 0
如果您的数据在一个漂亮的小数据框中,例如:
df <- tibble(string <- c("<params description=\"some desc\" bgcol=\"248;186;203\" col=\"0;200;0\"/>",
"<params description=\"some desc\" bgcol=\"255;0;0\"/>"))
那你就可以做
df %>% mutate(bgcol.value = str_extract(string, "\\d+;\\d+;\\d+"))
# A tibble: 2 x 2
`string <- c("<params description=\\"some desc\\" bgcol=\\"248;186;203\\" … bgcol.value
<chr> <chr>
1 "<params description=\"some desc\" bgcol=\"248;186;203\" col=\"0;200;0\"/>" 248;186;203
2 "<params description=\"some desc\" bgcol=\"255;0;0\"/>" 248;186;203
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.