chrisw
chrisw

Reputation: 407

Regex Group Matching

I am trying to match a pattern like so:

Pattern: (abc)(def)(ghi)h
Match:
Group 0 = [a,b,c]
Group 1 = [d,e,f]
Group 2 = [g,h,i]
Group 3 = h

Is it possible via regex to extrapolate the data into a list like that described?

The code being used is Python for reference.

Upvotes: 0

Views: 541

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170308

AFAIK, that's not possible in one regex. You could do something like this:

import re

matches = re.findall('[^()]+', '(abc)(def)(ghi)h')
map = []
for m in matches: 
  map.append(list(m))
for e in map:
  print e

which will print:

['a', 'b', 'c']
['d', 'e', 'f']
['g', 'h', 'i']
['h']

EDIT

The pattern [^()] matches any character other than a ( and ), so [^()]+ matches one or more characters other than ( and ).

Everything between a [ and ] is called a character class, and will always match just a single character. The ^ at the start makes it a negated character class (matches everything-but what is defined in it).

More info about character classes: http://www.regular-expressions.info/charclass.html

Upvotes: 2

Related Questions