Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select comma separated values between parentheses

Given the following simplified example text;

not me G(select me, and me)
G(select me) G(also me)

using regex expressions I would like to select everything between the G(...) as separate results even if there is, for example, a comma. Based on different answers here on SO this was my first attempt;

G\(([^)]+)\)

Works perfectly for second line but not so much for the first. My second attempt based on some other answers for selecting values from comma separated list;

G\(([^),]+)

Another attempt based on this SO, and another based on this SO.

Basically, I need help...

Expected output:

select me
and me
select me
also me
like image 672
tstev Avatar asked Sep 14 '26 09:09

tstev


2 Answers

Here is a way to do this in gnu awk. This appears more verbose but uses a fairly simple regex which doesn't depend on experimental PCRE regex option of gnu grep:

s="G(also me1) not me G(select me, and me) G(select me) G(also me)"
awk '{ 
   while ( match($0, /\<G\(([^)]*)\)(.*)/, a) ) {
      gsub(/ *, */, "\n", a[1])
      print a[1]
      $0 = a[2]
   }
}' <<< "$s"

also me1
select me
and me
select me
also me

Based on Ismail's comment below, if we want to make it POSIX compliant then use this awk command (because of non-availability of word boundary or \< in POSIX/BSD awk) :

awk '{
   while ( match($0, /(^|[[:blank:]])G\([^)]*\)/) ) {
      m=substr($0, RSTART+2, RLENGTH-3)
      sub(/^\(/, "", m)
      gsub(/ *, */, "\n", m)
      print m
      $0=substr($0, RSTART+RLENGTH)
   }
}' <<< "$s"
like image 70
anubhava Avatar answered Sep 16 '26 03:09

anubhava


With a GNU grep, you may use

(?:\G(?!^),\s*|\bG\()\K[^(),]+(?=[^()]*\))

See the regex demo.

Details

  • (?:\G(?!^),\s*|\bG\() - either the end of the previous match and a , followed with 0+ whitespace chars, or G( that has no letter, digit or _ right before
  • \K - omits the text matched so far
  • [^(),]+ - 1+ chars other than (, ) and ,
  • (?=[^()]*\)) - there must be 0+ chars other than ( and ) and then a ) immediately to the right of the current location.

See online demo:

rx='(?:\G(?!^),\s*|\bG\()\K[^(),]+(?=[^()]*\))'
example="not me G(select me, and me) G(select me) G(also me)"
grep -oP "$rx" <<< "$example"
# Also works with pcregrep: 
# pcregrep -o  "$rx" <<< "$example"

Output:

select me
and me
select me
also me
like image 25
Wiktor Stribiżew Avatar answered Sep 16 '26 05:09

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!