[英]How can I get an output out of a regular expression in JavaScript?
I am trying to create a very simple engine that will generate some random data based on a token. 我正在尝试创建一个非常简单的引擎,该引擎将基于令牌生成一些随机数据。
I was thinking that the input for the engine can be regex expressions so for example 我以为引擎的输入可以是正则表达式,例如
engine will get [0-9] will yield any random number like 9 9999 0897 000
engine will get \w will yield any random word (even without meaning) like asdd gwasss ttt were khhu encyclopedia
so if I want a random email, I will write an expression: 因此,如果我要随机发送电子邮件,我将写一个表达式:
\w@\w.com
for example random phone number 例如随机的电话号码
\d{3}-\d{3}-\d{4}
I am not sure how to approach this, Is there any JS library I can use to parse regex and override to get the output the way I want it? 我不确定如何处理这个问题,是否可以使用任何JS库解析正则表达式并重写以我想要的方式获取输出? Or do I need to write my own parser?
还是我需要编写自己的解析器?
pseudo code: 伪代码:
function getRandom('\d{3}-\d{3}-\d{4}');
will return 将返回
384-495-3344 or 433-244-3454 etc
Consider using an existing Regular Expression parser which outputs an AST . 考虑使用现有的输出AST的正则表达式解析器。
For example for JavaScript: 以JavaScript为例:
https://www.npmjs.com/package/regjsparser https://www.npmjs.com/package/regjsparser
https://github.com/jviereck/regjsparser https://github.com/jviereck/regjsparser
The demo page here allows you to see the generated AST: 此处的演示页面可让您查看生成的AST:
http://www.julianviereck.de/regjsparser/ http://www.julianviereck.de/regjsparser/
Then you could look through the "type" in the AST, in this case this includes the "dot" type: 然后,您可以浏览AST中的“类型”,在这种情况下,其中包括“点”类型:
{
"type": "dot",
"range": [
4,
5
],
"raw": "."
},
Also note there is a JS library to generate regular expressions from the AST: 另请注意,有一个JS库可从AST生成正则表达式:
https://www.npmjs.com/package/regjsgen https://www.npmjs.com/package/regjsgen
https://github.com/bnjmnt4n/regjsgen https://github.com/bnjmnt4n/regjsgen
PS: I posted a similar answer to this for a different problem here https://stackoverflow.com/a/57096632/406712 it might be worth a look. PS:我在https://stackoverflow.com/a/57096632/406712上针对另一个问题对此发布了类似的答案,可能值得一看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.