【问题标题】:RegExp(/[a-z\d]/g).test('5') is returning true or false each time? [duplicate]RegExp(/[a-z\d]/g).test('5') 每次都返回真还是假? [复制]
【发布时间】:2018-04-08 00:02:30
【问题描述】:

为什么这个正则表达式不能正常工作?

 new RegExp(/[a-z\d]/g).test('5');

结果有时为真,有时为假。 它不断在真/假之间切换

var regx = new RegExp(/[a-z\d]/g);

console.log(regx.test('5')) // true
console.log(regx.test('5')) // false
console.log(regx.test('5')) // true
console.log(regx.test('5')) // false

【问题讨论】:

  • 有时我认为 Javascript 是微软发明的(但公平地说,他们实际上开发了 Typescript,这很棒)
  • 正则表达式使用g修饰符是有状态的
  • match 没有状态
  • @bm_i 这种行为的用例是什么?

标签: javascript google-chrome


【解决方案1】:

这是因为结果从头开始:
lastIndex 属性显示它:在第一次找到 lastIndex=== 1 之后,但由于字符串的长度为 1,所以下一个搜索/测试是false,在字符串的末尾lastIndex 被“重置”为0)

var regx = new RegExp(/[a-z\d]/g);

console.log(regx.test('5'), regx.lastIndex) // true 1
console.log(regx.test('5'), regx.lastIndex) // false 0
console.log(regx.test('5'), regx.lastIndex) // true 1
console.log(regx.test('5'), regx.lastIndex) // false 0

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-31
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多