在javascript中使用RegExp查找混合大小写

时间:2017-04-05 03:27:49

标签: javascript regex case ignore

我想找'PM'或'P.M.'在输入字符串中作为忽略情况。 但这不起作用......

const pmRex = new RegExp('PM|P\.M\.', 'gi');

console.log(pmRex.exec('PM'));
console.log(pmRex.exec('Pm'));
console.log(pmRex.exec('pm'));
console.log(pmRex.exec('P.M.'));
console.log(pmRex.exec('P.m.'));
console.log(pmRex.exec('p.m.'));
console.log(pmRex.exec('p.M.'));
console.log(pmRex.exec('p.m'));

结果:

[ 'PM', index: 0, input: 'PM' ]
null
[ 'pm', index: 0, input: 'pm' ]
null
[ 'P.m.', index: 0, input: 'P.m.' ]
null
[ 'p.M.', index: 0, input: 'p.M.' ]
null

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是删除g标记,如果您无意实际使用它



const pmRex = /PM|P\.M\./i;

console.log('PM', pmRex.test('PM'));
console.log('Pm', pmRex.test('Pm'));
console.log('pm', pmRex.test('pm'));
console.log('P.M.', pmRex.test('P.M.'));
console.log('P.m.', pmRex.test('P.m.'));
console.log('p.m.', pmRex.test('p.m.'));
console.log('p.M.', pmRex.test('p.M.'));
console.log('p.m', pmRex.test('p.m'));




来自documentation ...

  

如果正则表达式使用"g"标志,则可以多次使用exec()方法在同一字符串中查找连续匹配。执行此操作时,搜索从正则表达式str属性

指定的lastIndex子字符串开始

否则,为了在具有全局标志的不同字符串上重复执行exectest,您需要重置lastIndex属性



const pmRex = /PM|P\.M\./gi;

console.log('PM', pmRex.test('PM'));
pmRex.lastIndex = 0;

console.log('Pm', pmRex.test('Pm'));
pmRex.lastIndex = 0;

console.log('pm', pmRex.test('pm'));
pmRex.lastIndex = 0;

console.log('P.M.', pmRex.test('P.M.'));
pmRex.lastIndex = 0;

console.log('P.m.', pmRex.test('P.m.'));
pmRex.lastIndex = 0;

console.log('p.m.', pmRex.test('p.m.'));
pmRex.lastIndex = 0;

console.log('p.M.', pmRex.test('p.M.'));
pmRex.lastIndex = 0;

console.log('p.m', pmRex.test('p.m'));