Laurent C.
Laurent C.

Reputation: 206

expr does not return the pattern if not at the beginning of the string

Using this version of bash:

GNU bash, version 4.1.2(1)-release (i386-redhat-linux-gnu)

How can I get expr to find my pattern within a string, if the pattern I'm looking for does not begin this string?

Example:

expr match "123 abc 456 def ghi789" '\([0-9]*\)' #returns 123 as expected
expr match "z 123 abc 456 def ghi789" '\([0-9]*\)' #returns nothing

In the second example, I would expect 123 to be returned.

Further analysis:

If I start from the end of the string by adding .* in my command, I get a weird result:

expr match "123 abc 456 def ghi789" '.*\([0-9]*\)' #returns nothing
expr match "123 abc 456 def ghi789" '.*\([0-9]\)' #returns 9 as expected
expr match "123 abc 456 def ghi789 z" '.*\([0-9]\)' #returns also 9

Here, it seems that the pattern can be found at the end of the string (so at the beginning of my search), and also if it's not at the end of the string. But it does not work if I add the * at the end of the regular expression.

In the other hand, the same does not apply if I start from the beginning of my string:

expr match "z 123 abc 456 def ghi789" '\([0-9]\)' #returns nothing

I think I must misunderstand something obvious, but I cannot find what.

Thank you for your help :)

Upvotes: 1

Views: 162

Answers (1)

Kleidersack
Kleidersack

Reputation: 478

Would expr match "123 abc 456 def ghi789 z" '[^0-9]*\([0-9]*\) do it? (Just added [0-9]* instead of .* at the beginning)

Like mentioned in the comments - the expression

expr match "123 abc 456 def ghi789 z" '^[^0-9]*\([0-9]*\) 

would fit better, because the part ^[^0-9] can be read as "skip all characters which are not digits ([^0-9]) form begin (the ^as first character)"

Upvotes: 1

Related Questions