Ari
Ari

Reputation: 4191

Bash Regex Capture

I'd like to capture portions of strings that match a regular expression (see code below). For example given: apply plugin: 'java' I'd like to capture java.

I've put together the following regex. When I execute the code below (on Linux or Mac OS) a match is found, but the BASH_REMATCH array is empty (i.e. length of zero).

Does anyone know what is wrong with the regex and/or its application?

regex="^[[:space:]]*apply[[:space:]]*plugin:[[:space:]]*'([[:alpha:]]+)'[[:space:]]*$"

if [[ "$line" =~ $regex ]]; then
  echo "Match count is ${#BASH_REMATCH[@]}."
  echo ${BASH_REMATCH[1]}
else
  echo "No match."
fi

Upvotes: 2

Views: 2297

Answers (1)

that other guy
that other guy

Reputation: 123610

I'm unable to reproduce this as posted on macOS. You might have a debug trap or similar set.

To help debug this, please edit your question to include:

  1. The complete script that you run (i.e. including whatever populates $line)
  2. The complete command you use to run it, and the complete output
  3. bash xtrace (-x) output

I expanded your code into a MCVE using information from your comments:

$ cat myfile
regex="^[[:space:]]*apply[[:space:]]*plugin:[[:space:]]*'([[:alpha:]]+)'[[:space:]]*$"

line="apply plugin: 'java'"

if [[ "$line" =~ $regex ]]; then
  echo "Match count is ${#BASH_REMATCH[@]}."
  echo ${BASH_REMATCH[1]}
else
  echo "No match."
fi

Then I ran it like this and got expected output:

$ bash myfile
Match count is 2.
java

Here's the output with debug info on:

$ bash -x myfile
+ regex='^[[:space:]]*apply[[:space:]]*plugin:[[:space:]]*'\''([[:alpha:]]+)'\''[[:space:]]*$'
+ line='apply plugin: '\''java'\'''
+ [[ apply plugin: 'java' =~ ^[[:space:]]*apply[[:space:]]*plugin:[[:space:]]*'([[:alpha:]]+)'[[:space:]]*$ ]]
+ echo 'Match count is 2.'
Match count is 2.
+ echo java
java

Here's system info:

$ uname -a && bash --version
Darwin hostname 17.4.0 Darwin Kernel Version 17.4.0: Sun Dec 17 09:19:54 PST 2017; root:xnu-4570.41.2~1/RELEASE_X86_64 x86_64
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin17)
Copyright (C) 2007 Free Software Foundation, Inc.

I can add reproduce the same results by e.g. adding trap '[[ a =~ b ]]' DEBUG to the script. If you're doing something like that, it will show up in the -x output.

Upvotes: 3

Related Questions