V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
pheyer
V2EX  ›  程序员

生成正则表达式

  •  
  •   pheyer · 2017-11-02 11:22:23 +08:00 · 3730 次点击
    这是一个创建于 2338 天前的主题,其中的信息可能已经有所发展或是发生改变。

    一堆文本中想去找一些特定字符串,需要用到正则,正则之前看过一些又忘了很多,然后又去查正则基础知识,觉得太难又放弃,打开某个网站发贴正则求助,是不是很多人都有这样的感觉?

    写正则难,看懂别人写的正则也难,忽然就萌生了能不能用编程语言或者自然语言自动生成正则表达式的想法,比如写出下面的代码:

    var str;
    if(var.hasPrefix(start) , var.hasSuffix(end))
    

    生成 ^start.*end$ 这样的正则表达式 这个当然是太简单了

    搜了一下,发现别人还真有做生成正则表达式的东西,然后就搜出了这么一大堆东西,分享一下吧😂

    1). http://www.txt2re.com/index.php3

    https://coolshell.cn/articles/1830.html 这里做了介绍,然而没看懂

    2).自动生成正则表达式 | WooYun 知识库

    这是一篇关于自动生成正则表达式的理论实践文章

    3). RE-Build:用自然语言去编写正则表达式 - luoyjx - 搞起博客

    4). VerbalExpressions/PHPVerbalExpressions: PHP Regular expressions made easy

    JS 的:VerbalExpressions/JSVerbalExpressions: JavaScript Regular expressions made easy

    各种语言都有,能生成正则表达式,感觉规则不全 例子:

    // Create an example of how to test for correctly formed URLs
    var tester = VerEx()
        .startOfLine()
        .then('http')
        .maybe('s')
        .then('://')
        .maybe('www.')
        .anythingBut(' ')
        .endOfLine();
    
    // Create an example URL
    var testMe = 'https://www.google.com';
    
    // Use RegExp object's native test() function
    if (tester.test(testMe)) {
        alert('We have a correct URL'); // This output will fire
    } else {
        alert('The URL is incorrect');
    }
    
    console.log(tester); // Outputs the actual expression used: /^( http)(s)?(\:\/\/)(www\.)?([^\ ]*)$/
    

    5).mbasso/natural-regex: Create regex from natural language

    有 Wiki:How to Use · mbasso/natural-regex Wiki 这个看起来规则很全,但是不能生成正则表达式

    例子:

    import NaturalRegex from 'natural-regex';
    // validate string
    const dateAndEmail = NaturalRegex.from('starts with dd/MM/yyyy, space, minus, space and then email, end.');
    dateAndEmail.test('06/07/2016 - [email protected]'); // this evaluates true
    dateAndEmail.test('Foo Bar foo@bar'); // this evaluates false
    

    6). 其它的

    自己动手写一个简单正则表达式解析器(待续,未完成)-极客学院

    如果能写自然语言生成正则表达式,又能输入正则表达式生成自然语言,正则的学习门槛会降很低吧

    1 条回复    2017-11-02 11:41:34 +08:00
    imdong
        1
    imdong  
       2017-11-02 11:41:34 +08:00
    正则表达式本身是很简单的,之不过一堆看起来无序的字符串比较容易让人懵逼而已。

    搞这些,其实真心不如静下心来花个把小时看一下正则表达式。

    然后你就会发现,还是特么工具好用(雾)

    表示我在 http://deerchao.net/tutorials/regex/regex.htm 上看了一会,就可以开搞了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2417 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 16:08 · PVG 00:08 · LAX 09:08 · JFK 12:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.