Python正则表达式:匹配没有公路名称的汽车速度

2024-10-03 09:14:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图匹配高速公路车票的速度描述,例如,文本行:

“L A 16-25 mph”应返回2组:16、25
“LMT ACC 6-10”应返回2组:6、10
“6过”应返回1组:6

我对上面所有的情况都没问题,但是我遇到了与速度无关的数字字符串的问题,例如:

“LIMITED ACCESS SPEED I-75”不应返回匹配项。
我能获得的最接近的表达式是:((?<!\w-)\d+)[^\d]*((?<!\w-)\d+)?,它将匹配1组:5,使用python正则表达式引擎

现在,可以肯定地假设一个字母然后一个连字符(\w-)是我试图使用负回溯来排除的,我只是不知道如何组合多个数字(\d+)来使用负回溯。你知道吗


Tags: 字符串引擎文本access表达式情况数字高速公路
2条回答

Negative lookbehinds必须具有固定的长度(有关详细信息,请参见Python doc),因此\d+之类的内容是不允许的。你知道吗

不过,您可以使用lookback检查高速公路的某些固定宽度指示器,例如IRT(不区分大小写)。您可能还需要添加额外的案例,以便在破折号周围添加空格,完全没有破折号,等等

一个可能符合条件的选项(设置不敏感标志):(?<!i|rt)(\d+)

说明

([0-9]+)(?:-([0-9]+)|\s*over)

Regular expression visualization

**要更好地查看图像,只需右键单击图像并选择“在新窗口中查看”

此正则表达式将执行以下操作:

  • 匹配与速度相关的数字
  • 避免使用属于道路名称的数字

示例

现场演示

https://regex101.com/r/hE5dL4/2

示例文本

注:关于I-75的边大小写

'm trying to match speed descriptions of highway tickets, for example,text lines:

"L A 16-25MPH" should return 2 groups: 16, 25 
"LIMITED ACCESS SPEED I-75" should return no matches.
"LMT ACC 6-10" should return 2 groups: 6, 10 
"6 OVER" should return 1 group: 6

I'm OK with all of the above situations, but I run into issues for strings with numbers that aren't related to speed, for example:

"LIMITED ACCESS SPEED I-75" should return no matches.

样本匹配

MATCH 1
1.  [89-90] `16`
2.  [91-93] `25`

MATCH 2
1.  [193-194]   `6`
2.  [195-197]   `10`

MATCH 3
1.  [231-232]   `6`

解释

NODE                     EXPLANATION
                                   
  (                        group and capture to \1:
                                   
    [0-9]+                   any character of: '0' to '9' (1 or more
                             times (matching the most amount
                             possible))
                                   
  )                        end of \1
                                   
  (?:                      group, but do not capture:
                                   
    -                        '-'
                                   
    (                        group and capture to \2:
                                   
      [0-9]+                   any character of: '0' to '9' (1 or
                               more times (matching the most amount
                               possible))
                                   
    )                        end of \2
                                   
   |                        OR
                                   
    \s*                      whitespace (\n, \r, \t, \f, and " ") (0
                             or more times (matching the most amount
                             possible))
                                   
    over                     'over'
                                   
  )                        end of grouping
                                   

相关问题 更多 >