Добавил поддержку символьных классов (кроме исключающих) и групп.
<meta charset="utf-8">
<form id="form">
<p><label>Регулярка:</label><input name="input"> <button name="run" type="button">Герерировать</button></p>
<p><label>Результат:</label><input name="output"></p>
</form>
<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 form = document.forms.form;
form.run.onclick = function() {
var root = parse(form.input.value);
form.output.value = generateMatchingString(root.tree);
}
});
var charClasses = {
'd': {ranges: ['09']},
's': {chars: ' \f\n\r\t\v'},
'w': {ranges: ['09', 'az', 'AZ'], chars: '_'}
};
function rangeToChars(range) {
var chars = '';
for (var i = range.charCodeAt(0); i < range.charCodeAt(1); i++) {
chars += String.fromCharCode(i);
}
return chars;
}
function classToChars(charClass) {
var chars = '';
var derivedChars = charClasses[charClass];
if (derivedChars.chars)
chars += derivedChars.chars;
if (derivedChars.ranges)
chars += derivedChars.ranges.map(rangeToChars).join('');
return chars;
}
function charSet(chars, classes, ranges) {
chars += classes.map(classToChars).join('');
chars += ranges.map(rangeToChars).join('');
return chars;
}
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[Math.round(Math.random()*node.branches.length)]);
},
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) {
var chars = charSet(node.chars, node.classes, node.ranges);
return chars[Math.round(Math.random()*chars.length)];
},
group: function(node) {
return generateMatchingString(node.sub);
}
};
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>