0

I have a following requirement that needs to be achieved in .bat file. Can some one please help.

There is a string, ABCD-1234 TEST SENTENCE in a variable, say str. Now I want to check if the string starts with format [A-Z]*-[0-9] * or not.

How can I achieve this? I tried various regular expression using FINDSTR, but couldn't get the desired result.

Example:

set str=ABCD-1234 TEST SENTENCE
echo %str% | findstr /r "^[A-Z]*-[0-9] *"
2
  • It does work. C:\Windows\system32>echo ABCD-1234 TEST SENTENCE | findstr /r "^[A-Z]*-[0-9] *" which shows ABCD-1234 TEST SENTENCE showing it matched. Commented Jan 4, 2017 at 4:32
  • 1
    FINDSTR regex capabilities are totally non-standard (and crippled). Describe exactly what search criteria you want, and give examples of strings that should match, as well as strings that should not. Commented Jan 4, 2017 at 4:37

1 Answer 1

2

I'm assuming you are looking for strings that begin with 1 or more upper case letters, followed by a dash, followed by 1 or more digits, followed by a space.

If the string might contain poison characters like &, <, > etc., then you really should use delayed expansion.

FINDSTR regex is totally non-standard. For example, [A-Z] does not properly represent uppercase letters to FINDSTR, it also includes most of the lowercase letters, as well as some non-English characters. You must explicitly list all uppercase letters. The same is true for the numbers.

A space is interpreted as a search string delimiter unless the /C:"search" option is used.

setlocal enableDelayedExpansion
echo(!str!|findstr /rc:"^[ABCDEFGHIJKLMNOPQRSTUVWXYZ][ABCDEFGHIJKLMNOPQRSTUVWXYZ]*-[0123456789][0123456789]* "

You should have a look at What are the undocumented features and limitations of the Windows FINDSTR command?

Sign up to request clarification or add additional context in comments.

3 Comments

Why is it necessary to state [0123456789] rather than [0-9]? I could not find any wrong (mis-)matches. I am aware of the [A-Z] flaw...
@aschipfl - From a practical standpoint, it is probably not necessary. But there are a few extended ASCII characters that lie within the range [0-9]. I believe they represent things like 1/2, 1/4, etc. So a precise solution does require [0123456789].
@aschipfl - You could use [0123-9] and still be precise, but it is not something I remember, so I just list all the digits. The [0-3] term is equivalent to [0¼½12²3].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.