我使用regex从地址字符串中提取字母“u”,但仅当它用作缩写(u,u.,u,u等)时。然而,我正在运行的问题是,我的字符串列表是混乱的,充满了错误。我已经试着从数据中找出我所需要的各种错误。我知道我一定错过了一些小东西,但任何帮助都是感激的。你知道吗
我试过这些正则表达式:
我还有另一个想法来解决这个问题,那就是需要分离地址(街道、号码等之间的分割),然后修复街道部分并将其粘在一起。我真的有点幸运,我只是把数字部分拔了出来:
但是,我想看看我在regex表达式中的混乱之处,它应该选择“u”。Regex101.com是我最好的朋友,没有它我不会走到现在。你知道吗
test_strings = [
"Holics u 5/a",
"Holics U 5/a",
"Holics u5/a",
"Huolics u 5/a",
"Holics u. 5/a",
"Holuics u5",
"Holics and other stuff u more stuff after 5",
"Houlics utca 5"
]
# two regex patterns I have considered
print("First regex pattern ------------------------------------")
pattern = r"[^\w+][uU]"
replacement_text = " utca "
for item in test_strings:
print(re.sub(pattern,replacement_text,item))
print("\nSecond regex pattern ------------------------------------")
pattern = r"[^\w+][uU][^tca]"
replacement_text = " utca "
for item in test_strings:
print(re.sub(pattern,replacement_text,item))
上述代码的结果:
第一个正则表达式模式:
Holics utca 5/a
Holics utca 5/a
Holics utca 5/a
Huolics utca 5/a
Holics utca . 5/a
Holuics utca 5
Holics and other stuff utca more stuff after 5
Houlics utca tca 5 # <-------------------------------- issue
第二个正则表达式模式:
Holics utca 5/a
Holics utca 5/a
Holics utca /a # <----------------------------------- issue
Huolics utca 5/a
Holics utca 5/a
Holuics utca <-------------------------------------- issue
Holics and other stuff utca more stuff after 5
Houlics utca 5
除了第一个regex模式中的最后一行(“Houlics utca tca 5”)之外,其他一切都正常工作,当我尝试创建一个表达式来考虑包含“utca”的字符串时,我丢失了像“Holics u5/a”这样的字符串中的数字
在很大程度上,我希望结果是:
最后一点,我有一些函数可以去掉句点和空格。你知道吗
你可以用
细节
\b
-词边界[uU]
-u
或U
(?=\b|\d)
-当前位置右侧必须有一个单词边界或一个数字\.?
-可选点\s*
-0+空格。你知道吗或者,您可以使用
参见regex demo和another regex demo。你知道吗
这里,如果下一个字符是字母,则
(?![^\W\d_])
失败,而不是数字要求。你知道吗相关问题 更多 >
编程相关推荐