[英]extract a substring where the characters next to it varies using regex in r
I have some strings like below. 我有一些像下面这样的字符串。 I need to extract color part from the strings. 我需要从字符串中提取颜色部分。
s1= 'color: red greenSize: 2 CountVerified Purchase'
s2= 'color: red greenVerified Purchase'
s3= 'color: red greenSize: 2 Count'
s4= 'color: red green'
I used str_replace
like below. 我使用了如下的str_replace
。 It only works for s1
and s3
. 它仅适用于s1
和s3
。 Not for s2
and s4
. 不适用于s2
和s4
。
str_replace(s1, 'color:\\s(.*)Size:\\s.*', '\\1')
Does anyone know how I can extract the colors from the string that work for ALL 4 cases? 有谁知道我该如何从适用于所有4种情况的字符串中提取颜色?
Here is my attempt using regmatches
, along with the following regex pattern: 这是我尝试使用regmatches
以及以下regex模式:
color: (\\S+) (\\S+)(?=Size|Verified|$)
This isolates the first and second colors, the second color's end being given by either the words Size
or Verified
, of the end of the string. 这将隔离第一和第二种颜色,第二种颜色的结尾由字符串末尾的单词Size
或Verified
给出。
x <- c("color: red greenSize: 2 CountVerified Purchase",
"color: red greenVerified Purchase",
"color: red greenSize: 2 Count",
"color: red green")
sapply(x, function(x) {
result <- regmatches(x, regexec("color: (\\S+) (\\S+)(?=Size|Verified|$)", x, perl=TRUE))[[1]]
c(result[2], result[3])
})
This outputs (a bit messy): 输出(有点混乱):
color: red greenSize: 2 CountVerified Purchase
[1,] "red"
[2,] "green"
color: red greenVerified Purchase color: red greenSize: 2 Count
[1,] "red" "red"
[2,] "green" "green"
color: red green
[1,] "red"
[2,] "green"
Is it just me or are all those colors in lowercase? 只是我还是所有这些颜色都是小写的? If this happens to be the case, you could simply do: 如果碰巧是这种情况,则可以执行以下操作:
pattern <- "color:\\s*([a-z ]+).*"
gsub(pattern, "\\1", your_strings_here)
See a demo on regex101.com . 参见regex101.com上的演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.