使用 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:
- colonK
- match reset operator that discards the whole text matched so far[^,]+
- 1+ chars other than,
这篇关于使用 grep 从键值对列表中提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文