How to extract a substring with findstr
Asked Answered
R

1

5

I'm trying to extract a substring with a Windows command.

I want to extract a number that looks like this: 1.2.3.4 or more exact [anyPosInteger.anyPosInteger.anyPosInteger.anyPosInteger].

I thought I was doing that with the regex.

Here is the code:

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%

Whould have been nice if the "foundstring" was "1.2.3.4".

findstr seem to only return the whole string when a match with regex has been found. What is more funny is that the regex that I have cunstructed does not seem to be liked by findstr.

This works "[0-9].[0-9].[0-9].[0-9]" but it still returns the whole string.

What am I doing wrong here? :)

/H

Raynaraynah answered 23/2, 2018 at 9:34 Comment(2)
findstr finds lines that contain the search pattern. It can't extract that pattern from the linesHindmost
would PowerShell be an option? If so, this would be trivialYuen
C
11

unfortunately findstr cannot be used to extract matches, and findstr does not support + as quantifier, you have to use:

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

but it will only return the whole line, for extracting regex match only i suggest you use powershell

"whatever 1.2.3.4 whatever talk to the hand" | Select-String -Pattern '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | % { $_.Matches } | % { $_.Value }
Councilman answered 23/2, 2018 at 11:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.