首页 > 解决方案 > 如何匹配异构的空白字符序列?

问题描述

例如:"\t\t \v"" \f"应该匹配。"\t\t\t"," "并且"\f\f\f"不应该匹配。

所以基本上,我想排除第一个捕获的字符,类似于 this (\s)\1*[^\S\1]+\s*。但这不起作用,因为我们不能将捕获的组放入[^].

我怎样才能做到这一点?

标签: pythonregex

解决方案


我不确定我是否正确满足了您的要求,但您可以尝试使用否定的 Lookahead:

(\s)\1*(?!\1)\s+

这样的事情对你有用吗?


这是一个 Python 示例:

regex = r"(\s)\1*(?!\1)\s+"
inputs = ["\t\t \v", "\f", "\t\t\t", " ", "\f\f\f", "\f \f"]

for s in inputs:
    if re.match(regex, s):
        print "Found a match."
    else:
        print ("No matches!")

输出:

Found a match.
No matches!
No matches!
No matches!
No matches!
Found a match.

如果不是,我不确定您为什么希望\f成为匹配项。如果这不是错误,你能澄清一下吗?


推荐阅读