首页 > 解决方案 > 带有条件边界的正则表达式?

问题描述

背景

我的问题的背景:查找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没有像我预期的那样考虑不良表达

请求帮忙

有没有一种简单的方法可以在一个正则表达式模式中实现它?谢谢

标签: pythonregex

解决方案


在单元之后使用负前瞻,这将检查是否没有 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'))    

推荐阅读