test for regex in string with a posix shell

2020-07-13 10:51发布

问题:

how can I test if a string matches a particular string matches regex with a basic (no bash or anything) posix shell script (in an if statement)?

回答1:

You can use expr command to evaluate regular expression in a POSIX shell:

s='Abc'
expr $s : '^[[:alpha:]]\+'

3

expr returns # of matched characters which is 3 in this case.