Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expressions in findstr

I'm doing a little string validation with findstr and its /r flag to allow for regular expressions. In particular I'd like to validate integers.

The regex

^[0-9][0-9]*$ 

worked fine for non-negative numbers but since I now support negative numbers as well I tried

^([1-9][0-9]*|0|-[1-9][0-9]*)$ 

for either positive or negative integers or zero.

The regex works fine theoretically. I tested it in PowerShell and it matches what I want. However, with

findstr /r /c:"^([1-9][0-9]*|0|-[1-9][0-9]*)$" 

it doesn't.

While I know that findstr doesn't have the most advanced regex support (even below Notepad++ which is probably quite an achievement), I would have expected such simple expressions to work.

Any ideas what I'm doing wrong here?

like image 867
Joey Avatar asked Apr 10 '10 15:04

Joey


People also ask

Does findstr support regex?

Regular Expressions (Search for patterns of text)FINDSTR support for regular expressions is limited and non-standard, only the following metacharacters are supported: . Wildcard: any character. * Repeat: zero or more occurances of previous character or class.

What does findstr command do?

The findstr (short for find string) command is used in MS-DOS to locate files containing a specific string of plain text.

How do I use findstr?

You can run findstr from the command line or as a batch file. Open a new command line prompt by clicking on the Windows-key, typing cmd.exe, and selecting the result. Alternatively, use the Run command to open findstr.

What is findstr in batch file?

The findstr command is a built-in command-line tool, which sends specific lines of matching words to the standard output device. Adding parameters to the findstr command gives you flexibility in finding words in files and even finding files.


2 Answers

This works for me:

findstr /r "^[1-9][0-9]*$ ^-[1-9][0-9]*$ ^0$" 

If you don't use the /c option, the <Strings> argument is treated as a space-separated list of search strings, which makes the space a sort of crude replacement for the | construct. (As long as your regexes don't contain spaces, that is.)

like image 138
Alan Moore Avatar answered Sep 22 '22 09:09

Alan Moore


Argh, I should have read the documentation better. findstr apparently doesn't support alternations (|).

So I'm probably back to multiple invocations or replacing the whole thing with a custom parser eventually.

This is what I do for now:

set ERROR=1 rem Test for zero echo %1|findstr /r /c:"^0$">nul 2>&1 if not errorlevel 1 set ERROR= rem Test for positive numbers echo %1|findstr /r /c:"^[1-9][0-9]*$">nul 2>&1 if not errorlevel 1 set ERROR= rem Test for negative numbers echo %1|findstr /r /c:"^-[1-9][0-9]*$">nul 2>&1 if not errorlevel 1 set ERROR= 
like image 37
Joey Avatar answered Sep 20 '22 09:09

Joey