Reputation: 390
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
Upvotes: 3
Views: 67
Reputation: 21275
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
Upvotes: 2
Reputation: 3961
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']
Upvotes: 2