ditheredtransparency
ditheredtransparency

Reputation: 585

Batch - Check if variable contains characters other than numbers, letters and hyphens

i am writing a script that sets a new computer name. the syntax is:

script.bat /NAME:<place new name here>

the issue is, im not sure how to get my script to verify that the user inputted only letters numbers and hyphens. so, basically, LENOVO-190 is ok, but LENOVO:~19|0) is not. Also, id like it to change all lowercase letters to capitals, just for aestetic affect (i think it looks nicer).

i only want my script to accept A-Z, 0-9, and -. and if an invalid character is inputted (lets say #), it will say something like "hey! # is not allowed!"

thanks everyone, cheers.

Upvotes: 1

Views: 3339

Answers (1)

AlexP
AlexP

Reputation: 4430

Modern versions of Windows have findstr, which is sort-of like grep in that it can look for matches of a regular expression. You can use it to check whether the input name matches your expectations. For example:

C> echo abcde| findstr /r /i ^^[a-z][a-z0-9-]*$ && echo Good name! || echo Only letters, digits and hyphens, please!
abcde
Good name!

C> echo ab#de| findstr /r /i ^^[a-z][a-z0-9-]*$ && echo Good name! || echo Only letters, digits and hyphens, please!
Only letters, digits and hyphens, please!

As to how to replace lower-case letters with upper-case letters in pure batchese, there are ways.

Upvotes: 4

Related Questions