Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expr string matching-mixed number and chars?

Tags:

regex

bash

When I typed

$ expr match "can't find" 'c'
$ 1

Then I typed

$ expr match "234can't find" 'c'
$ 0

I can't figure out why?

like image 447
Jack Chin Avatar asked Apr 14 '26 06:04

Jack Chin


1 Answers

The man page for the version of expr isn't very clear:

STRING : REGEXP
          anchored pattern match of REGEXP in STRING

match STRING REGEXP
          same as STRING : REGEXP

What, exactly, does "anchored" mean? The BSD version clears things up:

The regular expression is anchored to the beginning of the string with an implicit ``^''.

So expr match "234can't find" 'c' is identical to expr match "234can't find" '^c', and since your string doesn't begin with a c, the match fails.


Since bash supports regular expression matching natively, you can forgo the expr command in favor of

[[ "234can't find" =~ c ]]
like image 135
chepner Avatar answered Apr 16 '26 19:04

chepner