1

I was working on extraction of sub-string from the beginning & at the end of the string. I experimented with and with out ".*"

$expr "ab1cd1efgfedcbaAAAA" : ".*\(1[a-l]*\)"  # Result: 1efgfedcba

$expr "ab1cd1efgfedcbaAAAA" : "\(1[a-l]*\)"    # No Result (1cd was expected)

$expr "ab1cd1efgfedcbaAAAA" : "\(ab1[a-l]*\)"    # Result: ab1cd

Why did't the 'expr' give result for the second substring search.

It can be seen that 'ab' had been prefixed to the substring in the third search. that is the only difference between 2nd and 3rd search. Perhaps i am missing something here.

How is the search performed by 'expr' ?

8

man expr says the "STRING : PATTERN" expression is "anchored", and then in the info page (info coreutils 'expr invocation') you can read:

`STRING : REGEX'
     Perform pattern matching.  The arguments are converted to strings
     and the second is considered to be a (basic, a la GNU `grep')
     regular expression, with a `^' implicitly prepended.  The first
     argument is then matched against this regular expression.

Which means the effect you see is expected behavior.

  • So does this mean that the REGEX search always starts from the beginning of the STRING ? Is there a way to search a substring from the middle of the string ? – Sudhish Vln Dec 2 '15 at 10:59
  • There doesn't seem to be an option in expr for "not anchored" match. Depending on the system you are targetting, you can use your shell capabilities, sed, or awk to to do the same thing. Check mywiki.wooledge.org/BashFAQ/073 for some examples. – AlvaroGMJ Dec 2 '15 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.