我对正则表达式和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 "
。
有人可以解释第一和第二结果是如何产生的以及它们为何不同?
答案 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.