Converting user input string to regular expression

前端 未结 11 1829
无人及你
无人及你 2020-11-22 14:18

I am designing a regular expression tester in HTML and JavaScript. The user will enter a regex, a string, and choose the function they want to test with (e.g. search, match,

相关标签:
11条回答
  • 2020-11-22 14:38
    var flags = inputstring.replace(/.*\/([gimy]*)$/, '$1');
    var pattern = inputstring.replace(new RegExp('^/(.*?)/'+flags+'$'), '$1');
    var regex = new RegExp(pattern, flags);
    

    or

    var match = inputstring.match(new RegExp('^/(.*?)/([gimy]*)$'));
    // sanity check here
    var regex = new RegExp(match[1], match[2]);
    
    0 讨论(0)
  • 2020-11-22 14:38

    Thanks to earlier answers, this blocks serves well as a general purpose solution for applying a configurable string into a RegEx .. for filtering text:

    var permittedChars = '^a-z0-9 _,.?!@+<>';
    permittedChars = '[' + permittedChars + ']';
    
    var flags = 'gi';
    var strFilterRegEx = new RegExp(permittedChars, flags);
    
    log.debug ('strFilterRegEx: ' + strFilterRegEx);
    
    strVal = strVal.replace(strFilterRegEx, '');
    // this replaces hard code solt:
    // strVal = strVal.replace(/[^a-z0-9 _,.?!@+]/ig, '');
    
    0 讨论(0)
  • 2020-11-22 14:39

    Try using the following function:

    const stringToRegex = str => {
        // Main regex
        const main = str.match(/\/(.+)\/.*/)[1]
        
        // Regex options
        const options = str.match(/\/.+\/(.*)/)[1]
        
        // Compiled regex
        return new RegExp(main, options)
    }
    

    You can use it like so:

    "abc".match(stringToRegex("/a/g"))
    //=> ["a"]
    
    0 讨论(0)
  • 2020-11-22 14:40

    Use the JavaScript RegExp object constructor.

    var re = new RegExp("\\w+");
    re.test("hello");
    

    You can pass flags as a second string argument to the constructor. See the documentation for details.

    0 讨论(0)
  • 2020-11-22 14:46

    Use the RegExp object constructor to create a regular expression from a string:

    var re = new RegExp("a|b", "i");
    // same as
    var re = /a|b/i;
    
    0 讨论(0)
提交回复
热议问题