Пример генерации номера телефона по шаблону:
<script src="http://libs.useso.com/js/require.js/2.1.11/require.min.js"></script>
<script>
require.config({
baseUrl: "http://jex.im/regulex",
});
require(['dest/parse'], function(parse) {
var re = '\\+7 \\(\\d{3}\\) \\d{3}\\-\\d{2}\\-\\d{2}';
var root = parse(re);
alert(generateMatchingString(root.tree));
});
var randomClass = {
'd': function() {
return Math.round(Math.random() * 9);
}
}
var generateNode = {
exact: function(node) {
return node.chars;
},
dot: function(node) {
return String.fromCharCode(65 + Math.round(Math.random() * 25));
},
choice: function(node) {
return generateMatchingString(node.branches[0]);
},
repeat: function(node) {
var result = [];
for (var i = 0; i < node.repeat.min; i++) {
result.push(generateNode[node.type](node));
}
return result.join('');
},
charset: function(node) {
if (node.classes) {
return randomClass[node.classes[0]]();
}
}
};
function generateMatchingString(tree) {
var chunks = tree.map(function(node){
if (node.repeat)
return generateNode.repeat(node);
else
return generateNode[node.type](node);
});
return chunks.join('');
}
</script>