gpt4 book ai didi

regex - 如何使用 findstr 提取子字符串

转载 作者:可可西里 更新时间:2023-11-01 09:47:09 24 4
gpt4 key购买 nike

我正在尝试使用 Windows 命令提取子字符串。

我想提取一个看起来像这样的数字:1.2.3.4 或更精确的 [anyPosInteger.anyPosInteger.anyPosInteger.anyPosInteger]

我以为我是用正则表达式做的。

代码如下:

set mystring="whatever 1.2.3.4 whatever talk to the hand"  
echo %mystring% | findstr /r "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" >foundstring
echo %foundstring%

如果“foundstring”是“1.2.3.4”就好了。

findstr 似乎只在找到与正则表达式匹配时才返回整个字符串。更有趣的是,我构造的正则表达式似乎并不被 findstr 喜欢。

这对“[0-9].[0-9].[0-9].[0-9]”有效,但它仍然返回整个字符串。

我在这里做错了什么? :)

/H

最佳答案

很遗憾 findstr 不能用于提取匹配项,并且 findstr 不支持 + 作为量词,你必须使用:

findstr /R "[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*"

但它只会返回整行,仅用于提取正则表达式匹配我建议你使用 powershell

"whatever 1.2.3.4 whatever talk to the hand" | Select-String -Pattern '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | % { $_.Matches } | % { $_.Value }

关于regex - 如何使用 findstr 提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48944841/

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