python - 从字符串中提取特定的正则表达式结果
问题描述
我正在尝试从字符串中提取零件号。我将遍历项目,如果项目长度超过 4 个字符,并且至少包含 1 个数字,则需要提取该项目。它不必包含字母,但可以。
例如:
Line1: 'There is some random information here'
Line2: 'This includes item p23344dd5 as well as other info'
Line3: 'K3455 $100.00'
Line4: 'Last part number here 5551234'
我需要的是提取 3 个项目编号 p23344dd5、K3455 和 5551234。
我正在使用此代码,但它只会在匹配时返回,这不是我需要的。我需要返回匹配的文本。
import re
items = ['There is some random information here',
'This includes item p23344dd5 as well as other info',
'K3455 $100.00',
'Line4: ''Last part number here 5551234']
for item in items:
x = re.search(r'^(?=.*\d).{5,}$', item)
print(x)
解决方案
要匹配问题中的值,您可以从空白边界声明至少 5 个单词字符,然后匹配至少一个数字。
(?<!\S)(?=\w{5})[^\W\d]*\d\w*(?!\S)
解释
(?<!\S)
左边的空白边界(?=\w{5})
断言 5 个单词字符[^\W\d]*
匹配没有数字的可选单词字符\d
匹配 1 位数字\w*
匹配可选的单词字符(?!\S)
在右侧断言空白边界
import re
items = ['There is some random information here',
'This includes item p23344dd5 as well as other info',
'K3455 $100.00',
'Line4: ''Last part number here 5551234']
for item in items:
x = re.search(r'(?<!\S)(?=\w{5})\w*\d\w*(?!\S)', item)
if x:
print(x.group())
p23344dd5
K3455
5551234
推荐阅读
- c# - 根据适合相同内容的内容拆分内容
- php - 为什么 composer.json 需要 PHP 7.4 但服务器正在运行 PHP 7.3 不会中断部署?
- node.js - 无法让 'res.status(200).redirect('')' 工作
- java - 在 Spring Batch 中读取 CSV 数据(创建自定义 LineMapper)
- php - Codeigniter 致命错误:未找到接口“App\Model\ModeInterface”
- javascript - 如何在每一行中添加一个类名而不影响其余行?
- python - pylint/jedi 的 Cloud9 python 版本
- r - 我可以使用 KableExtra 添加可以直观地描绘列组的线条吗?
- python - 闰年python脚本
- python - 根据相互数量对网络中用户之间的连接进行分组