最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Two different regular expressions in one? - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Jun 6, 2011 at 2:42 Alan Moore 75.2k13 gold badges107 silver badges160 bronze badges asked May 28, 2011 at 14:56 NirNir 2,6399 gold badges47 silver badges75 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

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

  • /(?<style1>A)|(?<style2>B)/flags -- returns {.., groups:{style1:..?, style2:..?}}
  • /(?:A|B)arony?/flags -- matches "Aaron" or "Barony", avoiding capturing anything
  • /(A|B)arony?/flags -- matches "Aaron" or "Barony", capturing result
  • /A|B/flags -- you can do this without parentheses, but but you may encounter precedence issues with longer expressions*
    • (... more specifically, | binds loosely with low precedence (like + in 1+2*3=7), not tightly/not with high precedence (not like * in 1+2*3=7); so in the example above you'd have to type out Aaron|barony)

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 ments)

This is good practice for regexes that are being 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

You can OR-them this:

XX(XX)-XXXXXX(X)|*XXXX

so that either will match...

the trouble you get is that when the second one matches you don't get \1 ($1) and \2 ($2) set...

Use an | (or).

i.e.:

/^([0-9]{2,4})\-([0-9]{6,7})|(\*([0-9]{4})$/
发布评论

评论列表(0)

  1. 暂无评论