【发布时间】:2014-08-31 04:56:17
【问题描述】:
所以我对该主题进行了一些研究,但并没有找到完美的解决方案。 例如,我在变量中有一个字符串。
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
并不是真正的解决方案,因为我不一定需要比赛的最后一部分。
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"
EDIT3: 使用“look-behind assertions”几乎可以解决该问题,例如:
(?<=a)\d
不会返回字母“a”,只返回后面的数字,但需要固定长度,例如不能用作:
(?<=\w+)\d
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"
任何进一步的建议仍然很感激:)
【问题讨论】: