How to loop all the elements that match the regex?

前端 未结 8 1520
囚心锁ツ
囚心锁ツ 2020-12-02 18:27

Here is the case: I want to find the elements which match the regex...

targetText = \"SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext\"

相关标签:
8条回答
  • 2020-12-02 18:43

    I did this in a console session (Chrome).

    > let reg = /[aeiou]/g;
    undefined
    > let text = "autoeciously";
    undefined
    > matches = text.matches(reg);
    (7) ["a", "u", "o", "e", "i", "o", "u"]
    > matches.forEach(x =>console.log(x));
    a
    u
    o
    e
    i
    o
    u
    
    0 讨论(0)
  • 2020-12-02 18:49
    targetText = "SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext"    
    reg = new RegExp(/e(.*?)e/g);   
    var result;
    while (result = reg.exec(targetText))
    {
        ...
    }
    
    0 讨论(0)
  • 2020-12-02 18:50

    Try using match() on the string instead of exec(), though you could loop with exec as well. Match should give you the all the matches at one go. I think you can omit the global specifier as well.

    reg = new RegExp(/e(.*?)e/);   
    var matches = targetText.match(reg);
    
    0 讨论(0)
  • 2020-12-02 18:53

    I was actually dealing with this issue. I prefer Lambda functions for about everything.

    reg = /e(.*?)e/gm;   
    var result = reg.exec(targetText);
    
    result.forEach(element => console.log(element));
    
    0 讨论(0)
  • 2020-12-02 18:55

    You could also use the String.replace method to loop through all elements.

    result = [];
     // Just get all numbers
    "SomeT1extSomeT2extSomeT3ext".replace(/(\d+?)/g, function(wholeMatch, num) {
      // act here or after the loop...
      console.log(result.push(num));
      return wholeMatch;
    });
    console.log(result); // ['1', '2', '3']
    

    Greetings

    0 讨论(0)
  • 2020-12-02 19:00

    I kept getting infinite loops while following the advice above, for example:

    var reg = /e(.*?)e/g;
    var result;
    while((result = reg.exec(targetText)) !== null) {
        doSomethingWith(result);
    }
    

    The object that was assigned to result each time was:

    ["", "", index: 50, input: "target text", groups: undefined]
    

    So in my case I edited the above code to:

    const reg = /e(.*?)e/g;
    let result = reg.exec(targetText);
    while(result[0] !== "") {
        doSomethingWith(result);
        result = reg.exec(targetText);
    }
    
    0 讨论(0)
提交回复
热议问题