我有一个测试RegExp的函数,但它会以相同的值返回一半的真值!
(我修改了代码以显示问题,因为在项目中,用户每次输入数字时都会触发该函数)
我在哪里错了?
intent.js文件:
var intentTags = [
{
desc: 'elenca numeri telefonici',
type: 'numero',
phrases: ['numero', 'numeri'],
regex: new RegExp( /(?<!\w)(nu?m?e?r?[oi]?)\b/, 'gi' )
},
]
module.exports = {
attivati: function attivati(digitato) {
return intentTags[0].regex.test( digitato )
}
}
nodejs文件:
var intent = require('./intent')
var val = "numeri"
var result1 = intent.attivati( val );
var result2 = intent.attivati( val );
var result3 = intent.attivati( val );
var result4 = intent.attivati( val );
var result5 = intent.attivati( val );
var result6 = intent.attivati( val );
console.log( val, "returns: ", result1, result2, result3, result4, result5, result6 );
预期结果: numeri返回:true true true true true true true
实际结果: numeri返回:true false true false true false
答案 0 :(得分:0)
就像@vlaz所说的那样,这是因为g
标志使正则表达式有状态,所以连续调用将产生不同的结果。
您需要从g
删除RegExp
看本例
var intentTags = [
{
desc: 'elenca numeri telefonici',
type: 'numero',
phrases: ['numero', 'numeri'],
regex: new RegExp( /(?<!\w)(nu?m?e?r?[oi]?)\b/, 'i' )
},
]
var val = "numeri"
var result1 = intentTags[0].regex.test( val );
var result2 = intentTags[0].regex.test( val );
var result3 = intentTags[0].regex.test( val );
var result4 = intentTags[0].regex.test( val );
var result5 = intentTags[0].regex.test( val );
var result6 = intentTags[0].regex.test( val );
console.log( val, "returns: ", result1, result2, result3, result4, result5, result6 );