I need to match text which has @, #, and any number in it. The characters can be in random position as long as they are in the text. Given this input:
abc@#d9
a9b#c@d
@@abc#9
abc9d@@
a#b#c@d
The regex should match the first 3 lines. Currently my regex is:
/@.*?#.*?[0-9]/
Which doesn’t work since it will only match the three chars in sequence. How to match the three chars in random order?
Found one of this ugly regex, if you really must use one:
/(?=.*@)(?=.*#)(?=.*[0-9]).*/http://jsfiddle.net/BP53f/2/
The regex is basically using what they call
lookaheadhttp://www.regular-expressions.info/lookaround.html
A simple case from the link above is trying to match
q, followed byu, by doingq(?=u), that’s why it’s calledlookahead, it findsqfollowed byuahead.Let’s take one of your valid case:
a9b#c@dThe first lookahead is
(?=.*@), which states: Match anything, followed by a@. So it does, which is the stringa9b#c, then since the match from the lookahead must be discarded, the engine steps back to the start of the string, which is ana. Then it goes to(?=.*#), which states: Match anything that is followed by#, then it finds it ata9b. etc. The difference between using lookahead and(a)(b)(c)is basically the stepping back.From the link above:
It is ugly because it’s difficult to maintain… You basically have 3 different sub-regex inside the brackets.