Python正则表达式条件匹配?

2024-09-30 10:27:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道这个词是否合适,但我正试图想出一些正则表达式,可以从数学表达式中提取系数和指数。表达式的格式为“axB+cxD+exF”,其中小写字母表示系数,大写字母表示指数。我有一个正则表达式,可以匹配这两个正则表达式,但我想知道是否可以使用两个正则表达式,一个匹配系数,一个用于指数。有没有一种方法可以在不匹配字母的情况下,将数字的一侧与字母匹配?例如,在“3x3+6x2+2x1+8x0”中,我需要 ['3','6','2','8'] 和 ['3','2','1','0']


Tags: 方法表达式格式字母情况数字数学大写字母
3条回答

还有另一种方法,不使用regex:

>>> eq = '3x3+6x2+2x1+8x0'
>>> op = eq.split('+')
['3x3', '6x2', '2x1', '8x0']
>>> [o.split('x')[0] for o in op]
['3', '6', '2', '8']
>>> [o.split('x')[1] for o in op]
['3', '2', '1', '0']

您可以使用positive look-ahead来匹配后面跟有其他内容的内容。要匹配系数,可以使用:

>>> s = '3x3+6x2+2x1+8x0'
>>> re.findall(r'\d+(?=x)', s)
['3', '6', '2', '8']

根据^{}模块的文档:

(?=...) Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.

对于指数,可以使用positive look-behind

^{pr2}$

同样,从文件中:

(?<=...) Matches if the current position in the string is preceded by a match for ... that ends at the current position. This is called a positive lookbehind assertion. (?<=abc)def will find a match in abcdef, since the lookbehind will back up 3 characters and check if the contained pattern matches.

>>> import re
>>> equation = '3x3+6x2+2x1+8x0'
>>> re.findall(r'x([0-9]+)', equation)
['3', '2', '1', '0']
>>> re.findall(r'([0-9]+)x', equation)
['3', '6', '2', '8']

相关问题 更多 >

    热门问题