Alexander Stippler
Alexander Stippler

Reputation: 73

matching text in brackets

A fairly simple goal - I thought: matching text in brackets which contains two comma-separated parts, like e.g.:
[first,second] That's the whole line, I used bash 4.1.

I tried a pattern match like this and tried to use BASH_REMATCH afterwards:

[[ "$file_contents" =~ ^[\ []\(.*\),\(.*\)\ []\ ]$ ]] && echo YES || echo NO

I tried several little modifications but got either no match at all or wrong contents of BASH_REMATCH.

What's wrong about the regular expression above?

Upvotes: 0

Views: 176

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 80921

This works in bash 3.2.25(1) from CentOS 5 but fails in bash 4.1.2(1) from CentOS 6:

$ file_contents="[word1 word2,word3 word4]"
$ [[ $file_contents =~ ^\\[([^,]+),([^]]+)\\] ]]; echo $?
0
$ declare -p BASH_REMATCH
declare -ar BASH_REMATCH='([0]="[word1 word2,word3 word4]" [1]="word1 word2" [2]="word3 word4")'
  • Start of string: ^
  • Literal open square bracket: \\[
  • Capture start: (
  • One or more of class of anything but comma: [^,]+
  • Capture end: )
  • Literal comma: ,
  • Capture start: (
  • One or more of class of anything but close square bracket: [^]]+
  • Capture end: )
  • Literal close square bracket: \\]

This works in bash 4.1.2(1) from CentOS 6 but fails in bash 3.2.25(1) from CentOS 5:

[[ $file_contents =~ ^\[([^,]+),([^]]+)\] ]]; echo $?
  • Start of string: ^
  • Literal open square bracket: \[
  • Capture start: (
  • One or more of class of anything but comma: [^,]+
  • Capture end: )
  • Literal comma: ,
  • Capture start: (
  • One or more of class of anything but close square bracket: [^]]+
  • Capture end: )
  • Literal close square bracket: \]

Upvotes: 1

Federico Piazza
Federico Piazza

Reputation: 30985

You can use a regex like this:

\[\w+,\w+\]

Working demo

enter image description here

Upvotes: 0

Related Questions