gpt4 book ai didi

regex - 将 grep linux 命令与 perl regex + 捕获组一起使用

转载 作者:IT王子 更新时间:2023-10-29 00:38:50 31 4
gpt4 key购买 nike

所以我对这个主题做了一些研究,但我没有找到完美的解决方案。例如,我在变量中有一个字符串。

var="a1b1c2"

现在我想做的是只匹配“a”后跟任何数字,但我只希望它返回“a”之后的数字匹配它的规则如

'a\d'

因为我只需要数字,所以我尝试了

'a(\d)'

也许它确实在某个地方捕获了它,但我不知道在哪里,这里的输出仍然是“a1”

我还尝试了一个非捕获组来忽略输出中的“a”,但在 perl 正则表达式中没有效果:

'(?:a)\d'

作为引用,这是我终端中的完整命令:

[root@host ~]# var="a1b1c2"
[root@host ~]# echo $var |grep -oP "a(\d)"
a1 <--output

可能没有 -P 也是可能的(一些非 perl 正则表达式格式),我感谢每一个答案:)

编辑:使用

\K

并不是真正的解决方案,因为我不一定需要比赛的最后一部分。

编辑 2:我需要能够获得比赛的任何部分,例如:

[root@host ~]# var="a1b1c2"
[root@host ~]# echo $var |grep -oP "(a)\d"
a1 <--output
but the wanted output in this case would be "a"

编辑 3:使用“后视断言”几乎可以解决问题,例如:

(?<=a)\d

不会返回字母“a”,只会返回后面的数字,但它需要固定长度,例如不能用作:

(?<=\w+)\d

编辑 4:迄今为止最好的方法是使用 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"

任何进一步的建议仍然很感激:)

最佳答案

After some testing I found out, that the pattern inside the look-behind assertion needs to be fixed length (something like (?<=\w+)something will not work, any suggestions?

因为我之前发布并删除了我的答案,因为你说它不符合你的需要:

大多数情况下,您可以通过使用 \K 来避免可变长度后视 .这将重置报告匹配的起点,并且不再包括任何先前使用的字符。 (丢弃到那时匹配的所有内容。)

使用 \K 的主要区别回顾是,回顾不允许使用量词:您要查找的内容的长度必须固定。但是\K可以放在模式中的任何位置,因此您可以使用任何量词。

正如您在下面的示例中看到的,在 lookbheind 中使用量词将不起作用。

echo 'foosomething' | grep -Po '(?<=\w+)something'
#=> grep: lookbehind assertion is not fixed length

所以你可以这样做:

echo 'foosomething' | grep -Po '\w+\Ksomething'
#=> something

要仅在两个模式之间获取子字符串,您可以将 Positive Lookahead 添加到组合中。

echo 'foosomethingbar' | grep -Po 'foo\K.*?(?=bar)'
#=> something

或者使用固定的 Lookbehind 结合 Lookahead。

echo 'foosomethingbar' | grep -Po '(?<=foo).*?(?=bar)'
#=> something

关于regex - 将 grep linux 命令与 perl regex + 捕获组一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24665994/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com