Search code examples
regexunixsearchstring-matching

How to use regular expression for letters and numbers with dashes


So this is what I have currently in my shell script. I am pretty bad at regular expressions.

echo $1 | grep -E '^[A-Z]${3}|^[0-9]${4}|^[ABCD]$'

I need my input like this:

./dlchek.sh ACV-1319-A

This is the general format: XYX-1111-A where XYX can be any letter, 1111 can be any number, and A has to be either (A,B,C,D). I am using unix by the way. I only need to check if the format is correct and exit with code 0 if it is correct or 1 if it is incorrect.

This is expected output: Where line 3 is the only one that worked because it followed format.

[you@blue final]$ ./dlcheck.sh ACV-13-A
[you@blue final]$ echo $?
1
[you@blue final]$ ./dlcheck.sh ACV-13119-A
[you@blue final]$ echo $?
1
[you@blue final]$ ./dlcheck.sh ACV-1319-A
[you@blue final]$ echo $?
0
[you@blue final]$ ./dlcheck.sh ACV-1319-Y
[you@blue final]$ echo $?
1

Solution

  • ^[A-Z]{3}-[0-9]{4}-[ABCD]$
    

    What are those $$ doing in there? too many endings. And those pipes?? Do like me, use https://regex101.com/ and you'll learn something every time..