澄清Python正则表达式

时间:2014-01-24 05:45:38

标签: regex python-3.x

我对正则表达式和sub在Python中如何工作有点困惑。 我有这个例子:

nw = "  textttt    "
nw = re.sub(r'\s+(textttt)\s+', r'\1 ', nw)

nw中的值为nw = "textttt "。 但是,如果我有:

nw = "  textttt    "
nw = re.sub(r'\s(textttt)\s', r'\1 ', nw)

nw的值为nw = " textttt "。 有人可以解释第一和第二结果是如何产生的以及它们为何不同?

2 个答案:

答案 0 :(得分:1)

为清楚起见,我们用数字代替空格:

import re
nw = "01textttt2345"

xx = re.sub(r'\d+(textttt)\d+', r'\1 ', nw)
print '[%s]' % xx  # [textttt ]

xx = re.sub(r'\d(textttt)\d', r'\1 ', nw)
print '[%s]' % xx  # [0textttt 345]

第一个表达式找到01textttt2345并将其替换为组(= textttt)的值加上空格。第二个只查找1textttt2并将其替换为textttt,而保持字符串的其余部分不变。

答案 1 :(得分:0)

\\s - works for single whitespace character
\\s+ - works for sequence of one or more whitespace characters.