使用grep从键值对列表中提取值 [英] Extract value from a list of key-value pairs using grep
本文介绍了使用grep从键值对列表中提取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含键值对列表的字符串,例如:"a:1,b:2,c:3".我想提取指定键的值,例如我将为"a"得到"1".我打算用这样的正则表达式来做到这一点:
I have a string containing a list of key-value pairs like this: "a:1,b:2,c:3". I would like to extract a value for a specified key so that e.g. I would get "1" for "a". I was planning to do it with a regex like this:
'(?<=(^|,)$KEY:)^,*'
,但是grep似乎不支持环视. (我什至不确定此正则表达式是否正常工作.)还有另一种方法吗?
but it seems grep doesn't support lookarounds. (I'm not even sure this regex works correctly.) Is there another way?
推荐答案
您可以使用
grep -oP "(?:^|,)$KEY:\K[^,]+"
-o
选项输出匹配项. -P
启用PCRE引擎.字符串插值必须使用双引号,以便可以对$KEY
进行插值.
The -o
option outputs matches. -P
enables PCRE engine. The double quotes are necessary for string interpolation so that $KEY
could be interpolated.
模式匹配:
-
(?:^|,)
-字符串或逗号开头 -
$KEY
-KEY
变量 -
:
-冒号 -
\K
-匹配重置运算符,该运算符将舍弃到目前为止已匹配的整个文本 -
[^,]+
-除,
以外的1个以上字符
(?:^|,)
- start of string or comma$KEY
- theKEY
variable:
- colon\K
- match reset operator that discards the whole text matched so far[^,]+
- 1+ chars other than,
这篇关于使用grep从键值对列表中提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文