开发者

How use group complement in Python?

I am looking for something like r"[^\1]" in Python. For example, I want to match words like "hello" in a text where every letter has been replaced by one other (ex: "a" by "z", "b" by "r", ...). "hello" can be "zcuuj", "prvva", ... I want to say to Python: "find me a word which begins with [a-z], then a letter which is not l开发者_运维百科ike the first, then the same two letters, then a letter wich is different of the others.

I've tried this pattern:

r"([a-z])([^\1])([^\1\2]){2}([^\1\2\3])"

(doesn't work)

This one:

r"([a-z])((?!\1))((?!\1|\2)){2}((?!\1|\2|\3])"

(doesn't work)


Try this here

^([a-z])(?!\1)([a-z])(?!(?:\1|\2))(([a-z])\4)(?!(?:\1|\2|\4))[a-z]

I tested it online here on rubular

The problem with your second example is, the negative lookahead assertion are non consuming. That means you need to consum the characters after you checked them. I do this here after every lookahead with the . and the references.

The problem with your first example is, that you cant put those references in character groups.

UPDATE: I updated my regex and the rubular link, because the first version would have allowed other characters than [a-z] after the first one.


According to the documentation you can use (?P<name>...) to create a named group that you can later reference using (?P=name).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜