【发布时间】:2021-02-17 13:15:10
【问题描述】:
我正在尝试构建一个匹配key=value 或value_only 的正则表达式,在key=value 的情况下,该值可能包含= 符号。键应该进入捕获组 1,值应该进入捕获组 2。R/stringr 中的示例,这是 ICU 引擎。我还没有找到任何贪婪、占有和懒惰的量词的组合来使它起作用。我错过了什么吗?
library(stringr)
data <- c(
"key1=value1",
"value_only_no_key",
"key2=value2=containing=equal=signs"
)
# Desired outcome:
result <- matrix(c(
"key1", "value1",
"", "value_only_no_key",
"key2", "value2=containing=equal=signs"
), ncol=2, byrow= TRUE)
# The non-optionality of = results in no match for #2
str_match(
data,
"(.*?)=(.*)"
)[,-1]
# Same here
str_match(
data,
"([^=]*?)=(.*)"
)[,-1]
# The optionality of =? lets the greedy capture 2 eat everything
str_match(
data,
"(.*?)=?(.*)"
)[,-1]
# This is better than nothing, but the value_no_key ends up in the first match
str_match(
data,
"([^=]*+)=?+(.*)"
)[,-1]
【问题讨论】: