3

I am trying to find all occurrences of either "_"+digit or "^"+digit, using the regex ((_\^)[1-9])

The groups I'd expect back eg for "X_2ZZZY^5" would be [('_2'), ('^5')] but instead I am getting [('_2', '_'), ('^5', '^')]

Is my regex incorrect? Or is my expectation of what gets returned incorrect?

Many thanks

** my original re used (_|\^) this was incorrect, and should have been (_\^) -- question has been amended accordingly

1
  • 2
    You have two sets of parenthesis, so you'll get two groups. Commented Jul 11, 2020 at 16:31

2 Answers 2

2

You have 2 groups in your regex - so you're getting 2 groups. And you need to match atleast 1 number that follows.

try this:

([_\^][1-9]+)

See it in action here

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

Comments

2

Demand at least 1 digit (1-9) following the special characters _ or ^, placed inside a single capture group:

import re

text = "X_2ZZZY^5"
pattern = r"([_\^][1-9]{1,})"
regex = re.compile(pattern)
res = re.findall(regex, text)
print(res)

Returning:

['_2', '^5']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.