gpt4 book ai didi

python - 是正则表达式错误还是我的代码错误?

转载 作者:太空宇宙 更新时间:2023-11-03 17:26:09 25 4
gpt4 key购买 nike

import re

def street_regex(street):
street_regex = ""

regex = re.compile("^(\p{L}[\p{L} -]*\p{L}(?: \d{1,4}(?: ?[A-Za-z])?)?\b)")
s = regex.search(street)

if s:
street_regex = s.group()
else:
street_regex = street

return street_regex

这就是我的代码。来 self 的一个 previous posts在这里我得到了我在代码中使用的正则表达式。但是,如果我调用我的函数,那么正则表达式将无法工作,并且我不会得到我想要的。 (请参阅上一篇文章以了解我的意思)。如果有帮助的话,我正在使用 Python 3.4。

最佳答案

您需要使用regex模块。你的正则表达式是正确的,但Python的默认正则表达式模块re不会支持这些\p{L}\p{N}类型PCRE 正则表达式模式。您可以使用 [a-zA-Z] 代替 \p{L}re 但它必须仅支持英文字母,而不是任何类型任何语言的字母 (\p{L})。

>>> import regex
>>> re.search(r'\p{L}+', 'foo')
>>> regex.search(r'\p{L}+', 'foo')
<regex.Match object; span=(0, 3), match='foo'>
>>>

关于python - 是正则表达式错误还是我的代码错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32540422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com