简体   繁体   English

Python - 正则表达式模式优先级 - 多组数字

[英]Python - Regex Pattern Priority - multiple groups of digits

my goal is to create a regex capable to handle this digits series:我的目标是创建一个能够处理这个数字系列的正则表达式:

0014 2139 2411
0003 2139 2411
0104 43
022

I'm trying to find a way to create a Regex syntax that will return a group of MAX 4 digits separated by space with MAX 3 repetition, giving result priority of full 4 digits match.我正在尝试找到一种方法来创建正则表达式语法,该语法将返回一组 MAX 4 位数字,由空格分隔,重复 MAX 3 次,结果优先级为完整的 4 位数字匹配。 For example if I have this text:例如,如果我有这个文本:

  0014434 2139 2411
  Some text line... bla bla
  0003 2139 2411
  0003 2039 2411
  0104 43
  xxxx      
  0223423423

I'd like the Regex will return: 0003 2139 2411我希望正则表达式返回:0003 2139 2411

In this case:在这种情况下:

001 2139 2411
0003 21
0104 43

I'd like Regex to return -> 0003 21我希望正则表达式返回 -> 0003 21

I tryed with \d{4} but on first line it founds 3 different match.我尝试使用\d{4}但在第一行它找到了 3 个不同的匹配项。 Thanks Regs感谢注册

UPDATE更新

As per guggested by @Abion, using this:根据@Abion 的猜测,使用这个:

(^\d{1,4}$|^\d{4} \d{1,4}$|^\d{4} \d{4} \d{1,4}$)

works exept for a series of 4 char + space:适用于一系列 4 char + space 的作品:

在此处输入图像描述

Regex:正则表达式:

(^\d{1,4}$|^\d{4} \d{0,4}$|^\d{4} \d{4} \d{0,4}$)

Using group conditionals, this pattern matches a digit group of one to four digits OR a digit group of four digits followed by a digit group of one to four digits OR two digit groups of four digits followed by a digit group of one to four digits.使用组条件,此模式匹配一到四位的数字组或四位的数字组后跟一到四位的数字组或两位四位的数字组后跟一到四位的数字组。 These criteria would eliminate the first line of your second example (a digit group of three digits followed by more digit groups) causing it to match the second line.这些标准将消除第二个示例的第一行(三个数字的数字组,后跟更多数字组),使其与第二行匹配。

Note, you must provide the re.MULTILINE option for this pattern to work.请注意,您必须提供re.MULTILINE选项才能使此模式起作用。

Example: https://regex101.com/r/H3vKJX/2示例: https://regex101.com/r/H3vKJX/2

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

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