findstr Windows command regular expression

user1380142 picture user1380142 · May 7, 2012 · Viewed 15.5k times · Source

Is there a way to search for 2 or more spaces in a row between letters, using findstr from the Windows command line?

Example:

Hello world!  - nomatch wanted
Hello  world! - match wanted

What is regular expression syntax?

Also, can you please help me to understand the following command line session (difference between [ ] and [ ]*; the second command returns nothing):

c:\1>findstr -i -r  "view[ ]*data.sub" "view data sub.acf"
View Data Sub.ACF:            "].DATE_STAMP)>=[Forms]![MainNav]![View Data Sub]"
View Data Sub.ACF:            "].DATE_STAMP)<[Forms]![MainNav]![View Data Sub]"

c:\1>findstr -i -r  "view[ ]data.sub" "view data sub.acf"

c:\1>

PS: Just curious; I know about awk, perl, C# etc., but what about findstr?

Answer

arx picture arx · May 7, 2012

If you just want to find two consecutive spaces:

findstr /C:"  " input.txt

Or in a case-insensitive regular expression:

findstr /R /I /C:"lo  wo" input.txt

The important bit is the /C: in front of the pattern. This tells findstr to treat the pattern as a literal string. Without it, findstr splits the pattern into multiple patterns at spaces. Which, in my experience, is never what you want.

Update

To do two or more spaces between letters:

findstr /R /I /C:"[a-z]   *[a-z]" input.txt

Note that there are three spaces in the pattern. This matches a letter, two spaces followed by zero or more spaces (i.e. two or more spaces) and another letter.