moodmosaic / Fare

Port of Java dk.brics.automaton and xeger, mostly used for generating strings that match a specific regular expression.
http://www.brics.dk/automaton/
MIT License
183 stars 43 forks source link

Positive lookahead? #50

Open santi77 opened 5 years ago

santi77 commented 5 years ago

I'm trying to get a random password with some restrictions, this is my regex

^(?=.\d)(?=.[a-z])(?=.[A-Z])(?=.[@$._*#&%]).{8,16}$

This regex says:

When I try to run this on Xeger the code hangs, It is possible to do this?

StefH commented 5 years ago

@santi77 - I think your pattern should be like:

string pattern = "^(?.\\d)(?.[a-z])(?.[A-Z])(?.[@$\\._\\*#&%]).{8,16}$";
string value = new Xeger(pattern).Generate();
santi77 commented 5 years ago

That works, thank you!!!

StefH commented 5 years ago

I've my doubts if this actually works. lookahead is not implemented

Also when using Rex (https://rise4fun.com/rex), I get this error: The following constructs are currently not supported: anchors \G, \b, \B, named groups, lookahead, lookbehind, as-few-times-as-possible quantifiers, backreferences, conditional alternation, substitution

So in your case, to generate a valid pattern, you can use like this:

"\\d{2,4}[a-z]{2,4}[A-Z]{2,4}[0-9a-zA-Z]{2,4}"

However this is not really random...

gregsdennis commented 2 years ago

This worked for me as well, but I don't understand why. The construct (?=.<something>) works for online regex validators, but (?.<something>) is reported as invalid yet it works in .Net. And it doesn't work for this online .net validator: http://regexstorm.net/tester

Looks like it's an issue with this lib. The first syntax works for validation (Regex) but not for generation (Xeger).

Note also that (?.(dog)) only ever creates string that start with a random char, then "dog", then more randomness. I'll never get "dog" in another position within the generated string, which is what (?=.*(dog)) allows.