python - 带有条件边界的正则表达式?
问题描述
背景
我的问题的背景:查找mA
所有大写/小写的所有单位。尽可能多的提示用户周围的字符被误用为ma/Ma/MA,方便用户查找和定位。
正如我们所知mA
,是用于电流的有效单位。为简单起见,我们只使用整数,所以文本中的每一行
case 1, only number and unit: 1mA
case 2, number and unit, space: 1mA current
case 3, number and unit, punctuation: 1mA,
case 4, number and unit, Unicode characters: 1mA电流I
是一个有效的表达式。
但
case 5, 1mAcurrent
应该是一个无效的表达式,因为在没有空格的单位后面不允许有英文字母
我的正则表达式尝试
那么在这种情况下正确的正则表达式是什么?我已经使用了以下文本中的每一行
case 5 is taken as a right one, this is wrong \d{1,}mA
case 4 is ignored \d{1,}mA\b
case 4 is ignored \d{1,}mA[^a-zA-Z]*\b
如您所读,没有一个是正确的。
我的复杂代码
这是我正在使用的python代码,你会发现我使用python的if-else
import re
text = '''
case 1, only number and unit: 1mA
case 2, number and unit, space: 2mA current
case 3, number and unit, punctuation: 3mA,
case 4, number and unit, Unicode characters: 4mA电流I
case 5, 5mAcurrent
'''
lst = text.split('\n')
lst = [i for i in lst if i]
pattern = r'(?P<QUANTITY>\d{1,}mA)(?P<TAIL>.{0,5})'
for text in lst:
for match in re.finditer(pattern, text):
if not re.match('[a-zA-Z]', match.group('TAIL')): # extra line
print(match.group('QUANTITY'), ', ', match.group('TAIL'))
哪个输出
1mA ,
2mA , curr
3mA , ,
4mA , 电流I
显然,case 5, 5mAcurrent
没有像我预期的那样考虑不良表达
请求帮忙
有没有一种简单的方法可以在一个正则表达式模式中实现它?谢谢
解决方案
在单元之后使用负前瞻,这将检查是否没有 alpha:
pattern = r'(?P<QUANTITY>\d+mA)(?![a-z])(?P<TAIL>.{0,5})'
# here __^^^^^^^^^
代码:
pattern = r'(?P<QUANTITY>\d+mA)(?![a-z])(?P<TAIL>.{0,5})'
for text in lst:
for match in re.finditer(pattern, text):
print(match.group('QUANTITY'), match.group('TAIL'))
推荐阅读
- twitter-bootstrap - 为什么基本的引导折叠按钮对我不起作用?
- javascript - 如何拆分带有任意参数的字符串?
- angular - 从输入中获取一个翻译参数,从角度对象中获取另一个翻译参数
- php - 基于 Laravel 数组的日期验证 after_or_equal 多个日期?
- c++ - C++:静态断言仿函数的参数是常量引用
- android - iOS 或 Android 锁定屏幕中的 Delphi 按钮
- python - 绘图时 pandas.to_datetime() 不是从 18:00 开始
- ruby-on-rails - 使用 Excon Rails 6.0.0 在生产中未发送 API 请求
- swift - 无法转换“NSLayoutAnchor”类型的值
' 到预期的参数类型 'NSLayoutAnchor - linux - 输出文件的自定义文件名,不使用附加后缀