-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'.

1
  • 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. Commented Mar 5, 2020 at 6:10

2 Answers 2

2

use a non-capturing regex group

re.findall(r'(?:NAME|GAME)(\D*)', str1) 
Sign up to request clarification or add additional context in comments.

Comments

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) 

3 Comments

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)?
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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.