Regular Expressions: How to get the effect of an AND THEN operator in compound expression?

前端 未结 3 1693
梦毁少年i
梦毁少年i 2021-01-23 09:11

I\'m struggling to work with regular expressions. I think I understand the individual expressions but combining something together has me completely stumped. I don\'t grasp th

3条回答
  •  萌比男神i
    2021-01-23 09:37

    The way I understand regex is that, unless specified otherwise intentionally e.g. an OR clause, everything you define as a regex is in the form of an AND. [a-z] will match one character, whereas [a-z][a-z] will match one character AND another character.

    Depending on your use case the regex below could be what you need. As you can see it captures everything between .

    <[1-5][0-9]>([\s\S]*?)<\/[1-5][0-9]>
    
    <[1-5][0-9]> matches  where number is between 00 and 59.
    [\s\S]*? matches every single character there is, including new lines, between zero and unlimited times.
     matches  where number is between 00 and 59.
    

    Here is a snippet returning everything between . It converts the matches to an array and gets the first capture group of the first match. The first capture group being everything between as you can see by the parenthesis in the regex itself.

    let str = '<10>Hello, world!';
    
    let reg = /<[1-5][0-9]>([\s\S]*?)<\/[1-5][0-9]>/g;
    
    let matches = Array.from( str.matchAll(reg) );
    
    console.log(matches[0][1]);

提交回复
热议问题