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
作为捕获组?
答案 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
的第二次运行中,exec
是re.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);