简体   繁体   English

python 正则表达式意外匹配组

[英]python regex unexpected match groups

I am trying to find all occurrences of either "_"+digit or "^"+digit , using the regex ((_\^)[1-9])我正在尝试使用正则表达式((_\^)[1-9])查找所有出现的"_"+digit"^"+digit

The groups I'd expect back eg for "X_2ZZZY^5" would be [('_2'), ('^5')] but instead I am getting [('_2', '_'), ('^5', '^')]我期望返回的组,例如"X_2ZZZY^5"将是[('_2'), ('^5')]但我得到的是[('_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 ** 我原来的重新使用(_|\^)这是不正确的,应该是(_\^) - 问题已相应修改

Demand at least 1 digit (1-9) following the special characters _ or ^ , placed inside a single capture group:在特殊字符_^之后要求至少 1 个数字 (1-9),放置在单个捕获组中:

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']

You have 2 groups in your regex - so you're getting 2 groups.您的正则表达式中有 2 个组 - 所以您有 2 个组。 And you need to match atleast 1 number that follows.并且您需要匹配至少 1 个以下数字。

try this:尝试这个:

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

See it in action here此处查看实际操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM