0

I have the following example text:

60CC
60 cc
60cc2
60CC(2)

and the following regex to match these instances:

(60\s?(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("(60\s?(cc)(\w|\(.\)){0,5})", text, flags=re.IGNORECASE)
4
  • Use match.group() Commented Mar 5, 2020 at 12:58
  • lets start with clarifications. What exactly do you need? if you want the first one, why just not use "60CC" as regex? Commented Mar 5, 2020 at 13:03
  • Note that when you repeat the capturing group, the value of the third group for this string 60CC(2)(3)(4) would be (4) and not (2)(3)(4) Commented Mar 5, 2020 at 13:04
  • You are getting None because of {0,...} which allows an empty string. Commented Mar 5, 2020 at 13:05

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you this does the trick! - I have used the non-capturing groups method

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.