-2
import re
string1 = 'NAME is foo' 
string2 = 'GAME is bar' 
re.findall(r'NAME|GAME(\D*)',str1)

Expected output is it should work for either of the keyword and produce the output accordingly like for string1 it should be 'is foo' and for string2 it should be 'is bar'.

hemanth30
  • 21
  • 5
  • Your regex can be described as follows: "match a) 'NAME' or b) 'GAME' followed by zero or more non-digits". You want, "match 'NAME' or 'GAME', followed by zero or more non-digits". In both cases the digits are placed in capture group 1. – Cary Swoveland Mar 05 '20 at 06:10

2 Answers2

2

use a non-capturing regex group

re.findall(r'(?:NAME|GAME)(\D*)', str1)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
1

One more approach

items =['NAME is foo' , 'GAME is bar'] 
for item in items:
    print(re.findall(r'(?<=NAME|GAME)\s(.*)',item))

output

['is foo']
['is bar']

Here is an explanation of the regex pattern:

(?<=NAME|GAME) Look for characters after 'NAME' or 'GAME' (look-behind assertion)
\s             After space (you can include this in the look-behind as (?<=NAME |GAME ) as well)
(.*)           Capturing group (what you are actually looking to capture)
moys
  • 7,747
  • 2
  • 11
  • 42
  • Considering that you are capturing the end of the string in a capture group, why use a positive lookbehind instead of simply a non-capture group `(?:NAME|GAME)`? – Cary Swoveland Mar 05 '20 at 06:00
  • I used `positive look-behind` out of intuition. Is there distinct advantage of using `non-capture group` instead of a `positive look-behind`? When I check the timings (on the sample given here) I get `1.36 µs ± 18.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)` with positive look-behind & `1.38 µs ± 29.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)` with non-capture group. – moys Mar 05 '20 at 06:43
  • I don't know. I do think a non-capture group reads better here, as one is accustomed to seeing a lookbehind preceding a match that is not captured and a non-capture (or capture) group preceding a match that is captured. – Cary Swoveland Mar 05 '20 at 07:07