0

I have a string which includes the text:

...,"names":"exampleName",...

I have the following if statement that checks if the regex pattern matches the string:

if [[ $string =~ names\":\"(\w+)\" ]]; then
      echo "Matches"
fi

The problem is the echo statement never get's executed, which essentially means that the regex didn't match.

Is there something I'm doing wrong here? Because it should match...

Cheers.

2
  • How is $string assigned?
    – suspectus
    Commented Mar 3, 2013 at 21:56
  • $string is assigned the output of: string=$(curl ...)
    – Nick
    Commented Mar 3, 2013 at 21:57

3 Answers 3

1

It's a quoting issue, see e.g this

Try:

$ string='...,"names":"exampleName",...'

$ re='names":"(\w+)"'

$ if [[ $string =~ $re ]]; then echo match; fi
match
1
  • Escaped quotes don't trigger string matching. His problem is likely due to the \w.
    – chepner
    Commented Mar 4, 2013 at 13:42
1

The problem here seems to be that you are using an unsupported character class identifier. As per reference 1 below, it appears that bash uses the POSIX character classes rather than the slash-escaped character classes used in vi and other places.

Rather than using \w you should use [[:alnum:]_] (alphanumerics plus the underscore). I'd say to use [[:word:]], but apparently not all versions of bash support that (as mine doesn't).

A version of your code modified appropriately would look like this:

string='...,"names":"exampleName",...'

if [[ $string =~ names\":\"([[:alnum:]_]+)\" ]]; then
  echo "Matches"
fi

References:

  1. http://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html
  2. http://www.regular-expressions.info/posixbrackets.html
0

Try:

if [[ $string =~ names\":\"[[:alnum:]_]+\" ]]; then 

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