简体   繁体   English

Python正则表达式仅在数字匹配时匹配

[英]Python regex matching only if digit

Given the regex and the word below I want to match the part after the - (which can also be a _ or space) only if the part after the delimiter is a digit and nothing comes after it (I basically want to to be a number and number only). 给定正则表达式和下面的单词,仅当定界符后面的部分是数字并且后面没有任何内容时,我想匹配-后的部分(也可以是_或空格)(我基本上想成为数字)和数字)。 I am using group statements but it just doesn't seem to work right. 我正在使用组语句,但似乎工作不正确。 It keeps matching the 3 at the beginning (or the 1 at the end if I modify it a bit). 它始终与开头的3相匹配(如果我稍加修改,则与结尾的1相匹配)。 How do I achieve this (by using grouping) ? 如何实现此目的(通过使用分组)?

Target word: BR0227-3G1 目标词: BR0227-3G1

Regex: ([AZ]*\\s?[0-9]*)[\\s_-]*([1-9][1-9]*) 正则表达式: ([AZ]*\\s?[0-9]*)[\\s_-]*([1-9][1-9]*)

It should not match 3G1, G1 , 1G 它不应与3G1,G1、1G匹配

It should match only pure numbers like 3,10, 2 etc. 它只能匹配3、10、2等纯数字。

Here is also a helper web site for evaluating the regex: http://www.pythonregex.com/ 这也是评估正则表达式的帮助网站: http : //www.pythonregex.com/

More examples: 更多示例:

It should match: 它应该匹配:

BR0227-3
BR0227 3
BR0227_3

into groups (BR0227) (3) 分组(BR0227) (3)

It should only match (BR0227) for 它仅应与(BR0227)匹配

BR0227-3G1
BR0227-CS
BR0227
BR0227-

I would use 我会用

re.findall('^([A-Z]*\s?[0-9]*)[\s_-]*([1-9][1-9]*$)?', str)

Each string starts with the first group and ends with the last group, so the ^ and $ groups can assist in capture. 每个字符串都从第一个组开始,最后一个组结束,因此^$组可以帮助捕获。 The $ at the end requires all numbers to be captured, but it's optional so the first group can still be captured. 最后的$要求捕获所有数字,但是它是可选的,因此仍可以捕获第一组。

Since you want the start and (possible) end of the word in groups, then do this: 由于您希望该单词的开头和结尾(可能)在组中,因此请执行以下操作:

r'\b([A-Z0-9]+)(?:[ _-](\d+))?\b'

This will put the first part of the word in the first group, and optionally the remainder in the second group. 这会将单词的第一部分放在第一组中,并将其余部分放在第二组中。 The second group will be None if it didn't match. 如果第二组不匹配,则为“ None

该名称应与后跟“-”,“”或“ _”且后面仅数字的任何内容匹配。

(.*)[- _](\d+)

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

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