3

Is it possibile with one regex to validate this string and extract all names :

Input :

daz.Da zD.{Azd} .{AZDza}; D
name:{franck}{steve}{louis}
zefzef{z'f'z} fze fzef zef

ouptut :

[0] "franck"
[1] "steve"
[2] "louis"

Here is what I got : name:(?:{(.*?)}) but I don't know how to repeat (one or more) this expression (?:{(.*?)}) to extract all name after name:.

I don't want to use regex python package that supports repeated capturing groups.

Louis Barranqueiro
  • 9,390
  • 6
  • 39
  • 51
  • Possible duplicate of [Capturing repeating subpatterns in Python regex](http://stackoverflow.com/questions/9764930/capturing-repeating-subpatterns-in-python-regex) – Remi Guan Nov 21 '15 at 12:20

2 Answers2

3

You can chain the matches by using the \G anchor with Python regex package.

It matches at the position where each search started/continued

(?:name:|\G(?!^)){([^}]+)}
  • (?:name:|\G(?!^)) first part: Match name: literally |\G or continue where the last match ended, (?!^) but not at start.

  • {([^}]+)} second part: Capture non} inside {...} to $1 glued to successfull previous match.

Use with regex.findall

See demo at regex101

bobble bubble
  • 11,625
  • 2
  • 24
  • 38
1

Not with a single regex but you may do like this,

>>> s = '''daz.Da zD.{Azd} .{AZDza}; D
name:{franck}{steve}{louis}
zefzef{z'f'z} fze fzef zef'''
>>> [j for i in re.findall(r'(?m)^name:(.*)', s) for j in re.findall(r'\{([^}]*)\}', i)]
['franck', 'steve', 'louis']

This would print all the names present inside the curly barces from the line which starts with name:

or

Use startswith

>>> s = '''daz.Da zD.{Azd} .{AZDza}; D
name:{franck}{steve}{louis}
zefzef{z'f'z} fze fzef zef'''.splitlines()
>>> [j for line in s  for j in re.findall(r'\{([^}]*)\}', line) if line.startswith('name')]
['franck', 'steve', 'louis']
Avinash Raj
  • 166,785
  • 24
  • 204
  • 249