Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows CMD's FINDSTR wrong regexp matching

I need to check if a string contains anything except the digit. But I've got a problem.

echo bdfbdfd | findstr /R [^0123456789]

returns nothing, but it should return bdfbdfd. But

echo 123 | findstr /R [^0123456789]

returns '123'. Why? It should work vice versa.

like image 799
michaeluskov Avatar asked Oct 01 '12 08:10

michaeluskov


2 Answers

After a lot of tests here we go:

echo 123 | findstr /R "[^0123456789]"
        ^ this space is what is matched, remove it and it won't match anything

Another way to do this is (as Christian.K stated) escaping the ^ thus writing

echo 123| findstr /R [^^0123456789]

(note the ^^)

For the bdfbdfd part putting the second regex between "" and removing the space makes it work for the specified string.

EDIT:

Note that you are matching a single character. In the match

echo bdfbdfd | findstr /R [^0123456789]

nothing was matched because your string didn't contain any digit (not counting the ^ which needed to be escaped). In

echo 123 | findstr /R [^0123456789]

you were matching the first digit. With your regex you'll match any string that contains a single match, so also trying to match 123(space) with the regex [^^0123456789] will output the whole string as a match because of the non-digit character in the end of the string.

like image 146
Gabber Avatar answered Nov 08 '22 17:11

Gabber


The ^ is the escape character of CMD.EXE.

You need to escape it with another one:

   echo xxxx | findstr /R [^^0123456789]

or use quotes around the pattern:

   echo xxxx | findstr /R "[^0123456789]"

Update: Actually the following part is wrong, as you are looking for "anything else then only digits". The following will not work for input strings like "1x", which obviously contain something except a digit. So the, probably, best solution is to use what @Gabber suggested, i.e. get rid of the space before the pipe.

   echo xxxx| findstr /R "[^0-9]"

Also, you need to remove either the space (see @Gabber's answer) before the | (pipe), or make sure that the pattern matches from the start of the line (you have a couple of options here):

   echo xxxx | findstr /R "^[^0123456789]"
   echo xxxx | findstr /R ^^[^^0123456789]
   echo xxxx | findstr /B /R "[^0123456789]"
   echo xxxx | findstr /B /R ^^[^^0123456789]

Finally, you could shorten your pattern by using [0-9] instead of listing all the digits:

   echo xxxx | findstr /B /R "[^0-9]"

You could still compress your pattern to a [0-9] though:

   echo xxxx| findstr /R "[^0-9]"
like image 38
Christian.K Avatar answered Nov 08 '22 16:11

Christian.K