Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regex unexpected match groups

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

like image 653
user908094 Avatar asked Apr 09 '26 21:04

user908094


2 Answers

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

like image 56
rdas Avatar answered Apr 12 '26 11:04

rdas


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']
like image 40
Gustav Rasmussen Avatar answered Apr 12 '26 10:04

Gustav Rasmussen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!