I am using regex to process some files, for example if I have the following lines, and I need to capture the Example number, and whether there is an ERROR or not.
Example 1: bla bla bla
Example 2: bla bla ERROR
Example 3: bla bla
I'm doing 'Example\s+(\d+):.*(?:ERROR)?'
, it gives me the Example number, but how can I know if ERROR
exists?
Update:
I change non-capture group to capture group, but it still doesn't work.
In [77]: line = 'Example 5: abv ERROR zyx'
In [78]: re.search('Example\s+(\d+).+(ERROR)?', line).group(2)
In [79]: re.search('Example\s+(\d+).+(ERROR)', line).group(2)
Out[79]: 'ERROR'
I am totally confused, the word is there but why the optional capture group is not capturing it?