Python regex outputting multiple matches
Question:
I have the following example text:
60CC
60 cc
60cc2
60CC(2)
and the following regex to match these instances:
(60s?(cc)(w|(.)){0,5})
however my output is as follows for the first match:
['60CC', 'CC', None]
(Demo of the sample regex & data.)
how do I limit the output to just the first item?
I am using Python Regex.
the snippet of my python code is:
re.findall("(60s?(cc)(w|(.)){0,5})", text, flags=re.IGNORECASE)
Answers:
how do I limit the output to just #1 ?
You can just ignore the irrelevant groups from your findall/finditer results.
Alternatively, use non-capturing groups for the bits you don’t care about: just add ?:
after the leading parenthesis, this way you can still use grouping features (e.g. alternation) without the group being captured (split out) in the result.
I have the following example text:
60CC
60 cc
60cc2
60CC(2)
and the following regex to match these instances:
(60s?(cc)(w|(.)){0,5})
however my output is as follows for the first match:
['60CC', 'CC', None]
(Demo of the sample regex & data.)
how do I limit the output to just the first item?
I am using Python Regex.
the snippet of my python code is:
re.findall("(60s?(cc)(w|(.)){0,5})", text, flags=re.IGNORECASE)
how do I limit the output to just #1 ?
You can just ignore the irrelevant groups from your findall/finditer results.
Alternatively, use non-capturing groups for the bits you don’t care about: just add ?:
after the leading parenthesis, this way you can still use grouping features (e.g. alternation) without the group being captured (split out) in the result.