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.

Nick
  • 1,269
  • 5
  • 31
  • 45

3 Answers3

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
Community
  • 1
  • 1
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
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
John Sherwood
  • 1,408
  • 1
  • 10
  • 5
0

Try:

if [[ $string =~ names\":\"[[:alnum:]_]+\" ]]; then 
Scrutinizer
  • 9,608
  • 1
  • 21
  • 22