如何使用findstr提取子字符串

时间:2018-02-23 09:34:49

标签: regex windows cmd findstr

我尝试使用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

1 个答案:

答案 0 :(得分:5)

遗憾的是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 }
相关问题