所以我对这个主题做了一些研究,但我找不到完美的解决方案.例如,我在变量中有一个字符串.
var="a1b1c2"
Run Code Online (Sandbox Code Playgroud)
现在我想要做的只是匹配"a"跟随任何数字,但我只希望它返回"a"之后的数字来匹配它的规则如
'a\d'
Run Code Online (Sandbox Code Playgroud)
因为我只需要数字,我试过
'a(\d)'
Run Code Online (Sandbox Code Playgroud)
也许它确实在某个地方捕获了它,但我不知道在哪里,这里的输出仍然是"a1"
我还尝试了一个非捕获组忽略输出中的"a",但在perl正则表达式中没有效果:
'(?:a)\d'
Run Code Online (Sandbox Code Playgroud)
作为参考,这是我的终端中的完整命令:
[root@host ~]# var="a1b1c2"
[root@host ~]# echo $var |grep -oP "a(\d)"
a1 <--output
Run Code Online (Sandbox Code Playgroud)
可能没有-P(一些非perl正则表达式格式)也可能,我很感谢每个答案:)
编辑: 使用
\K
Run Code Online (Sandbox Code Playgroud)
并不是真正的解决方案,因为我不一定需要比赛的最后部分.
EDIT2: 我需要能够获得比赛的任何部分,例如:
[root@host ~]# var="a1b1c2"
[root@host ~]# echo $var |grep -oP "(a)\d"
a1 <--output
but the wanted output in this case would be "a"
Run Code Online (Sandbox Code Playgroud)
编辑3: 使用"后视断言"几乎解决了问题,例如:
(?<=a)\d
Run Code Online (Sandbox Code Playgroud)
不会返回字母"a",只返回它后面的数字,但它需要一个固定的长度,例如它不能用作:
(?<=\w+)\d
Run Code Online (Sandbox Code Playgroud)
EDIT4: 到目前为止最好的方法是使用perl或结合使用后视断言和\ K但它似乎仍然有一些限制.例如:
1234_foo_1234_bar
1234567_foo_123456789_bar
1_foo_12345_bar
if "foo" and "bar" are place-holders for words that don't always have the same length,
there is no way to match all above examples while output "foobar", since the
number between them doesn't have a fixed length, while it can't be done with \K since we need "foo"
Run Code Online (Sandbox Code Playgroud)
任何进一步的建议仍然赞赏:)
hwn*_*wnd 18
经过一些测试后我发现,后视断言中的模式需要固定长度(类似的东西
(?<=\w+)something不起作用,有什么建议吗?
我之前发布并删除了我的回答,因为您说它不符合您的需求:
大多数情况下,您可以通过使用避免可变长度的lookbehinds\K.这将重置报告的匹配的起始点,并且不再包括任何以前消耗的字符.(抛弃与此相匹配的所有内容.)
使用\K和lookbehind 之间的关键区别在于,lookbehind不允许使用量词:你要查找的长度必须是固定的.但是\K可以放在模式中的任何位置,因此您可以使用任何量词.
正如您在下面的示例中所看到的,在lookbheind中使用量词将不起作用.
echo 'foosomething' | grep -Po '(?<=\w+)something'
#=> grep: lookbehind assertion is not fixed length
Run Code Online (Sandbox Code Playgroud)
所以你可以这样做:
echo 'foosomething' | grep -Po '\w+\Ksomething'
#=> something
Run Code Online (Sandbox Code Playgroud)
要仅在两个模式之间获取子字符串,可以将Positive Lookahead添加到混合中.
echo 'foosomethingbar' | grep -Po 'foo\K.*?(?=bar)'
#=> something
Run Code Online (Sandbox Code Playgroud)
或者使用固定Lookbehind与Lookahead结合使用.
echo 'foosomethingbar' | grep -Po '(?<=foo).*?(?=bar)'
#=> something
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7260 次 |
| 最近记录: |