如何使用 findstr 提取子字符串
How to extract a substring with 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
似乎只 return 整个字符串。更有趣的是,我构造的正则表达式似乎并不被 findstr 喜欢。
这适用于“[0-9].[0-9].[0-9].[0-9]”,但它仍然是 return 整个字符串。
我在这里做错了什么? :)
/H
不幸的是findstr
不能用于提取匹配,并且findstr
不支持+
作为量词,你必须使用:
findstr /R "[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*"
但它只会 return 整行,仅用于提取正则表达式匹配我建议你使用 powershell
"whatever 1.2.3.4 whatever talk to the hand" | Select-String -Pattern '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | % { $_.Matches } | % { $_.Value }
我正在尝试使用 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
似乎只 return 整个字符串。更有趣的是,我构造的正则表达式似乎并不被 findstr 喜欢。
这适用于“[0-9].[0-9].[0-9].[0-9]”,但它仍然是 return 整个字符串。
我在这里做错了什么? :)
/H
不幸的是findstr
不能用于提取匹配,并且findstr
不支持+
作为量词,你必须使用:
findstr /R "[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*"
但它只会 return 整行,仅用于提取正则表达式匹配我建议你使用 powershell
"whatever 1.2.3.4 whatever talk to the hand" | Select-String -Pattern '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | % { $_.Matches } | % { $_.Value }