Some questions about regularity

encounter an endless loop of code, ask God to explain why, thank you!

<script>
        var str = "110120119114";
        var pattern = /\d*/g //
        var total = 0,
            match ="",
            result;
        while((result = pattern.exec(str))!=null){
            match +=result[0]+","
            
        }
        console.log(match);
    
    </script>

canonical change to /\ dbadge g
/\ dbadge g can match 0 digits, so it won't stop, and there will be an endless cycle

. < hr >

ide/Regular_Expressions" rel=" nofollow noreferrer "> MDN regular expression
regular expression is used for to match a string that matches a certain pattern .
* indicates that the previous expression is matched 0 or more times.
so / c/g.test ("a string") indicates the string "a string" whether there is a c , and / c*/g.test ("a string") indicates the string "a string" whether has at least 0 c. Obviously has at least 0 that is absolutely true. So / c*/g.exec ("a string") will match at the very beginning (because you need at least 0, even if I start with a , I return 0 c`, that is, an empty string meets your requirements, if you use while to loop, I will always give you an empty string).

< hr >

regular is used to match strings that match a certain pattern.
for example, / b indicates a word boundary, and / string\ b/g.test ("strings") is false , because the string strings is followed by s after g , so it is not a word boundary. / string\ b/g.test ("string~") is true because g is followed by ~ , the word is over.
but this cannot say that there is a word boundary between g and ~ such things as / b . A string is just a simple string of characters, and string~ is just a string of characters such as s , t , r . ~ . / b whether there is a regular expression parser finds that your string~ is string , followed by ~ , and you have finished a word in string , so it determines that your string conforms to the pattern such as / string\ bswag .


var reg = /\d+/g;
var str = '110120119114';
var result = str.match(reg).join(',');

just one demand can still get in touch with the endless cycle, and he is also drunk.

something better

function parse(str) {
    var at = 0, len = str.length, results = [];
    while (at < len) {
        var ch = str[at];
        if (/\d/.test(ch)) {
            var number = '';
            while (ch && /\d/.test(ch)) {
                number += ch;
                ch = str[PPat];
            }
            number = parseFloat(number, 10);
            results.push(number);
        }
        atPP;
    }
    return results;
}
< hr >

regular expression? We don't need regular expressions, we just need a NFA

Menu