为什么此正则表达式的第二部分不匹配?

时间:2019-01-07 23:10:48

标签: javascript regex

var re = /\d(\d)/g;
var str = '123';
var match;
var results = [];

while (match = re.exec(str)) {
  results.push(+match[1]);
}
console.log(results);

它不像我期望的那样[2, 3],而仅给出[2],我无法弄清楚。为什么23不匹配正则表达式并赋予3作为捕获组?

2 个答案:

答案 0 :(得分:2)

这是因为字符串// users.js var express = require('express'); var router = express.Router(); //Get Login router.get('/login', function(req,res){ res.render('userlogin'); }); //Get Register router.get('/register', function(req,res){ res.render('userregister',{title:'Register'}); }); //Post Register router.post('/register', function(req,res){ var nam = req.body.name; console.log(nam); }); module.exports = router; //useregister.ejs <form method="POST" action="/register" > <div class="form-group"> </div> <div class="form-group"> <input type="text" name="name" placeholder="Name" required class="form-control input-lg" /> </div> <div class="form-group"> <input type="text" name="username" placeholder="Username" required class="form-control input-lg" /> </div> <div class="form-group"> <input type="text" name="email" placeholder="Email" required class="form-control input-lg" /> </div> <div class="form-group"> <input type="password" name="password" class="form-control input- lg" id="password" placeholder="Password" required="" /> </div> <div class="form-group"> <input type="password" name="password2" class="form-control input-lg" id="password2" placeholder="Confirm Password" required="" /> </div> <div class="pwstrength_viewport_progress"></div> <button type="submit" name="submit" class="btn btn-lg btn-primary btn-block">Sign Up</button> <div> <p> Have an account : <a href="/login">Login Here </a> </p> </div> </form> 12的第一轮中是匹配的,捕获的括号是exec,它附加在2变量和results后面lastIndex对象的属性更新为re

2的第二次运行中,execre.lastIndex,这意味着开始匹配索引为{{1}的源字符串,因此2的字符串为{{1 }}显然与模式2不匹配,并且exec返回re,而退出循环且3数组仅包含/\d(\d)/

答案 1 :(得分:0)

如何进行重叠匹配:

var re = /\d(?=(\d))/g;
var str = '123';
var match;
var results = [];

while (match = re.exec(str)) {
  results.push(+match[1]);
}
console.log(results);