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