regex - 使用正则表达式确保某些内容包含单独的数字
问题描述
我正在尝试在网站上抓取公司的位置。我有这个功能:
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
。
这可能吗?
解决方案
您可以使用以下模式来匹配出现在字符串中不同单词中的两个数字:
\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"
推荐阅读
- python - 将需要两个整数的映射函数应用于列表列表
- wso2 - 无需手动生成令牌即可调用 API
- python - 我正在用 python 学习 tensorflow2,我想知道 ndim 是什么设置的?
- python - 我将如何在 python3 中创建类似于 Minecraft 服务器控制台的东西
- javascript - webpack 无法解析 d.ts 文件
- wordpress - 重定向规则在 wp_redirect 函数中不起作用
- android - 创建新应用并在生成签名包方面需要帮助
- r-exams - 单个 R/考试练习中的不同类型的任务
- tailwind-css - Sveltekit Tailwind 配置变量不起作用
- python - TypeError: __array__() 采用 1 个位置参数,但在 Windows 10 的 venv 中安装 Tensorflow 2.5 后给出了 2 个