如何使用findstr提取子字符串

5

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

我想要提取一个看起来像这样的数字: 1.2.3.4 或更精确地说是 [任意正整数.任意正整数.任意正整数.任意正整数]

我以为可以用正则表达式实现。

以下是代码:

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 命令用于查找包含搜索模式的行,但它无法从这些行中提取出该模式。 - user330315
1
PowerShell是否是一个选项?如果是,那么这将是微不足道的。 - Mathias R. Jessen
1个回答

11

很不幸,findstr 不能用来提取匹配项,而且 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 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接