2017-04-05 6 views
0

'PM'또는 'P.M'을 찾고 싶습니다. 입력 문자열에서 대소 문자를 무시합니다. 그러나이 작동하지 않습니다 ...자바 스크립트에서 RegExp를 사용하여 대소 문자가 혼용 된 경우

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 

가 어떻게이 문제를 해결할 수 있습니까?

+0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec#Return_value 및 https://developer.mozilla.org/en-US/docs/Web/을 참조하십시오. JavaScript/Reference/Global_Objects/RegExp/exeC# Finding_successive_matches – Phil

+0

예상 결과가 '부울'입니까? 아니면 일치하는 문자열입니까? – guest271314

+1

'exec'의 순서를 변경해보십시오. 매 초마다 출력이 항상 null 인 것을 보게 될 것입니다. 이유를 찾으려면'exec' 문서를 확인하십시오. –

답변

0

가장 쉬운 해결책은 당신이 실제로 documentation에서 그것은

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'));

을 사용할 의도를했습니다없는 경우 일반 있다면 ...

g 플래그를 제거하는 것입니다 expression에 "g" 플래그가 사용되면 exec() 메서드를 여러 번 사용하여 연속적인 ma를 찾을 수 있습니다. 똑같은 문자열에 이렇게하면 검색이 글로벌 플래그 다른 문자열을 반복 exec 또는 test을 실행하기 위해,


그렇지 않으면 정규 표현식의 lastIndex 속성으로 지정된 str의 문자열에서 시작, 당신은 필요 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'));

+0

이것은 나에게 좋은 답변입니다. @Phil 감사합니다 :) –