javascriptregex

Two different regular expressions in one?


I want to put this regexs into one regex, but dont now how:

/^([0-9]{2,4})\-([0-9]{6,7})$/
/^\*([0-9]{4})$/

so the string can get XX(XX)-XXXXXX(X) or *XXXX

Thanks.


Solution

  • to merge two regular expressions A and B, do one of (ordered from best to worst practice):


    Named groups example #1

    > 'A'.match(/(?<style1>A)|(?<style2>B)/).groups
    {style1: 'A', style2: undefined}
    

    Named groups example #2 (with destructuring assignment)

    USERID_REGEX = /(?<style1>A)|(?<style2>B)/
    let {style1,style2} = myIdVariable.match()
    if (style1!==undefined)
        ...
    else if (style2!==undefined)
        ...
    else
        throw `user ID ${USERID_REGEX} failed regex match`;  // careful of info leak
    

    Named groups example #3 (with comments)

    This is good practice for regexes that are becoming too large to be intelligible to the programmer. Note that you must double-escape \ as \\ in a javascript string unless you use /.../.source (i.e. '\\d' == "\\d" == /\d/.source)

    USERID_REGEX = new RegExp(
        `^`  +'(?:'+    // string start
          `(?<style1>` +
             /(?<s1FirstFour>\d{2,4})-(?<s1LastDigits>\d{6,7})/.source  +    // e.g. 123?4?-5678901?
          `)` +
    
          '|' +
          
          /\*(?<s2LastFour>\d{4})/.source  +    // e.g. *1234
        ')$'    // string end
    );
    let named = '1234-567890'.match(USERID_REGEX).groups;
    if (named.style1)
        console.log(named.s1FirstFour);
    

    Or you could just type out USERID_REGEX = /^(?:(?<style1>(?<firstFour>\d{2,4})-(?<lastDigits>\d{6,7}))|\*(?<lastFour>\d{4}))$/.

    Output:

    1234