Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a substring with findstr

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

like image 537
user2034859 Avatar asked Dec 24 '22 09:12

user2034859


1 Answers

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 }
like image 134
manjeet Avatar answered Jan 09 '23 01:01

manjeet