首页 > 解决方案 > 使用正则表达式确保某些内容包含单独的数字

问题描述

我正在尝试在网站上抓取公司的位置。我有这个功能:

x=['174 WEST 4TH ST, NYC','All contents © Copyright 2018 Propela']

import re

def is_location(text):
    """Does text contain digits, lowercase and uppercase letters"""
    return all(re.search(pattern, text) for pattern in ['\d{3,16}', '[a-z]*', '[A-Z]'])
# x[1]
# is_location(x[2])

print(list(filter(is_location, x)))

我想使用正则表达式,并且以某种方式仅在两次提及数字时才捕获东西,因此由于在174 WEST 4TH ST, NYC中有一组数字174,然后是另一个单独的数字4

这可能吗?

标签: regexpython-3.x

解决方案


您可以使用以下模式来匹配出现在字符串中不同单词中的两个数字:

\d+.*\s+.*\d+

这是一个示例代码:

line = "174 WEST 4TH ST, NYC";

res = re.search( r'\d+.*\s+.*\d+', line, re.M|re.I)
if res:
    print "found a match: ", res.group()
else:
    print "no match"

推荐阅读