gpt4 book ai didi

regex - 如何使用sed从字符串中提取文本?

转载 作者:行者123 更新时间:2023-11-29 08:39:15 25 4
gpt4 key购买 nike

我的示例字符串如下:

This is 02G05 a test string 20-Jul-2012

现在我想从上面的字符串中提取02G05。为此,我用 sed 尝试了以下正则表达式

$ echo "This is 02G05 a test string 20-Jul-2012" | sed -n '/\d+G\d+/p'

但上面的命令没有打印任何内容,我认为原因是它无法将任何内容与我提供给 sed 的模式进行匹配。

所以,我的问题是我在这里做错了什么以及如何纠正它。

当我用 python 尝试上面的字符串和模式时,我得到了我的结果

>>> re.findall(r'\d+G\d+',st)
['02G05']
>>>

最佳答案

使用 grep -E 怎么样?

echo "This is 02G05 a test string 20-Jul-2012" | grep -Eo '[0-9]+G[0-9]+'

关于regex - 如何使用sed从字符串中提取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11568859/

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