为什么我的regexp坏了?

2024-06-28 14:37:44 发布

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

我是个新手。我使用python3.3过滤带有模块re的地址。你知道吗

我想知道为什么会出现以下regex

m3 = re.search("[ ,]*[0-9]{1,3}\s{0,1}(/|-|bt.)\s{0,1}[0-9]{1,3} ",Row[3]);

匹配字符串,如:

rue de l’hotel des monnaies 49-51 1060Bxl
av Charles Woeste309 bte2 -Bxl
Rue d'Anethan 46 bte 6
Avenue Defré 269/6

但不匹配字符串,如(m3 is None):

Avenue Guillaume de Greef,418 bte 343
Joseph Cuylits,24 bte5 Rue Louis
Ernotte 64 bte 3
Rue Saint-Martin 51 bte 7

这对我来说真的很奇怪。 欢迎解释。 非常感谢。你知道吗


Tags: 模块字符串research地址deregexm3
1条回答
网友
1楼 · 发布于 2024-06-28 14:37:44

似乎正则表达式末尾的尾随空格“”是无意的,并且正在破坏某些东西:"[ ,]*[0-9]{1,3}\s{0,1}(/|-|bt.)\s{0,1}[0-9]{1,3} "

正则表达式检索正在寻找以下方法(建议您use the ^{} flag to allow you to put comments inside a regex,这样它不会很快变成只读;-)。请注意,将多行字符串“”与重复详细信息现在意味着我们甚至不能插入“”字符(您必须使用[]或\s)

import re

addr_pat = re.compile("""
    [ ,]*       # zero or more optional leading space or commas
    [0-9]{1,3}  # 1-3 consecutive digits
    \s{0,1}     # one optional whitespace (instead you could just write \s?)
    (/|-|bt.)   # either forward-slash, minus or "bt[any character]" e.g. "bte"
    \s{0,1}     # one optional whitespace
    [0-9]{1,3}  # 1-3 consecutive digits
                # we omitted the trailing " " whitespace you inadvertently had
""", re.VERBOSE)

m3 = addr_pat.search("Rue Saint-Martin 51 bte 7 ")

对尾随空格的要求是以下各项不匹配的原因:

Avenue Guillaume de Greef,418 bte 343
Joseph Cuylits,24 bte5 Rue Louis
Ernotte 64 bte 3
Rue Saint-Martin 51 bte 7

相关问题 更多 >