Search code examples
pythonregex-grouppython-re

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


Solution

  • 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