如何编写正则表达式用空字符串替换零,并确保没有前导数字

时间:2015-04-05 11:55:17

标签: python regex

我想要一个正则表达式用0替换0 * x ** n但是我想确保0之前没有数字

我希望在此公式中替换

0 * x**2 + 20 * x**1

我想用''替换0 * x ** 2

我写了一个正则表达式,但是它替换了所有的零乘以x ** 2它在' 2'之后删除了零。在' 20'

这是我的正则表达式

[+]?[ ]?0 [*] [a-z][*]{2}\d+

谢谢

2 个答案:

答案 0 :(得分:1)

这是模式:

import re
r = re.compile(r'(^|\s)0 \* x\*\*([0-9]+) [\-+] ')

这就是你用正则表达式取代的方式:

the_str = '0 * x**2 + 20 * x**1'
new_str = r.sub('', the_str)

请注意,如果它为零,则不会清除最后一个成员。这将留下一个" +"来自前一个成员,因此应该单独处理。

也赢得了匹配" 0 * x ** - 2",负指数。这留给读者一个练习:)

模式分解:

'(^|\s)0 \* x\*\*([0-9]+) [\-+] '
 ------- -- -----________ -----
    |_____|___|______|_____|____ match zero that is preceeded by beggining of the string or a space, to awoid matching things like "10 * x**2"
          |   |      |     |
          |___|______|_____|____ match asterisk, needs to be escaped because it's a special char in regex syntax
              |      |     |
              |______|_____|____ match literal x**
                     |     |
                     |_____|____ match one or more (that's what "+" means) chars in range of 0-9 (i.e. digits)
                           |
                           |____ match - or +, minus should be escaped here since it indicates a range of chars (as in [0-9])
Spaces match spaces.

答案 1 :(得分:0)

您可以使用:

import re
string = "0 * x**2 + 20 * x**1";
string = re.sub(r'([^0-9]|^)0 \* [a-z]\*\*[0-9]+', '0', string)
print(string)

输出:

0 + 20 * x**1

模式匹配非数字字符或行([0-9]|^)的开头,后跟要替换的字符序列:0 \* x\*\*[0-9]+