python常规如何用Letter匹配一个点?

时间:2013-04-28 13:55:05

标签: python regex

我想要匹配字符串,如:

what.are you doing?

匹配在一个点后面有一些字母 并替换“。”用“。”

结果如:
what. are you doing?

更多示例

输入

uh....i don't know

输出

uh.... i don't know

输入

do you know....that thing?

输出

do you know.... that thing?

2 个答案:

答案 0 :(得分:7)

这应该适合你的情况:

re.sub(r'(?<=\S)\.(?=\w)', '. ', s)

这使用一个正向的lookbehind断言(?<=...)来检查点前面是否有非空格字符\S。正向后置断言(?=\w)检查点后面是否有字母数字字符。

答案 1 :(得分:0)

我很晚才这么做。虽然,想分享另一种选择:

re.sub(r'\.(\w)', '. \\1', s)

Explanation:
\.(\w)
|   |
|   ----> catch an alphabet letter in group '()' which is referenced later in replacement by \\1 (because it's 1st caught group)
escape '.'

希望有所帮助:)