Regex to match permuted set of characters

别说谁变了你拦得住时间么 提交于 2019-12-23 01:26:31

问题


I want to match strings which begin with all six characters abcdef, regardless of the order in which these six characters occur at the beginning of the string.

All six characters must appear once, and once only, in the first six characters of the string, to produce a match.

e.g. "dfabce..." is a match, but "aacdef..." is not.

Can regular expressions do this, or do I need a parser?


回答1:


Sure, you could do this with positive lookahead assertions:

^(?=.{0,5}a)(?=.{0,5}b)(?=.{0,5}c)(?=.{0,5}d)(?=.{0,5}e)(?=.{0,5}f).*

This will ensure that the letters a through f each appear in the first 6 characters of the string.

Or with a negative lookahead assertion:

^(?!(.).{0,4}\1|.(.).{0,3}\2|..(.).?.?\3|...(.).?\4|....(.)\5)[a-f]{6}

Yeah, I know this looks a little crazy, but basically, it will ensure that the first 6 characters are a through f and that the first, second, third, or fourth, or fifth character are not duplicated within the first 6 characters. You need to have so many different alternations because you don't want the lookahead condition to 'bleed' past the first 6 characters (i.e. you want to match "dfabcee").

Or alternatively, if your chosen platform supports it, you could use a lookbehind:

^(([a-f])(?<!\2.*\2)){6}

This will ensure that the first 6 characters are a through f and that they do not appear after instance of the same character.



来源:https://stackoverflow.com/questions/24891868/regex-to-match-permuted-set-of-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!