How to generate random strings that match a given regexp?

前端 未结 5 674
花落未央
花落未央 2020-12-08 08:10

Duplicate:

Random string that matches a regexp

No, it isn\'t. I\'m looking for an easy and universal method, one that I could actu

5条回答
  •  -上瘾入骨i
    2020-12-08 08:37

    if your only criteria are that your method is easy and universal, then there ain't nothing easier or more universal than brute force. :)

    for (i = 0; i < 10; ++i) {
        do {
            var str = generateRandomString();
        } while (!myRegex.match(str));
        myListOfGoodStrings.push(str);
    }
    

    Of course, this is a very silly way to do things and mostly was meant as a joke.

    I think your best bet would be to try writing your own very basic parser, teaching it just the things which you're expecting to encounter (eg: letter and number ranges, repeating/optional characters... don't worry about look-behinds etc)

提交回复
热议问题