둘 이상의 문자열을 정규식과 어떻게 일치시킬 수 있습니까?여러 시퀀스를 일치시키는 방법
여기서 name
과 txt
을 모두 일치시키고 싶지만 name
만 일치합니까? 대신
var reg = new RegExp('%([a-z]+)%', "g");
reg.exec('%name% some text %txt%');
둘 이상의 문자열을 정규식과 어떻게 일치시킬 수 있습니까?여러 시퀀스를 일치시키는 방법
여기서 name
과 txt
을 모두 일치시키고 싶지만 name
만 일치합니까? 대신
var reg = new RegExp('%([a-z]+)%', "g");
reg.exec('%name% some text %txt%');
g 플래그가 작업을 수행하지만, 필요 동일한 문자열 여러번
var reg = new RegExp('%([a-z]+)%', "g");
var str = '%name% some text %txt%';
var result;
while(result = reg.exec(str)) { // returns array of current match
console.log(result[1]); // index 0 is matched expression. Thereafter matched groups.
}
상기 출력 콘솔 name
& txt
실행될.
예 here
사용 match
:
'%name% %txt%'.match(reg); //["%name%", "%txt%"]
만 (캡처 그룹이기는하지만) 첫 경기를 검색합니다.
캡처 그룹이 당신에게 중요하다면, 당신은 루프 사용할 수 있습니다 만 캡처 그룹을 유지하려면
var matches = [];
var str = '%name% some text %txt%';
var reg = new RegExp('%([a-z]+)%', "g");
while (match = reg.exec(str)){
matches.push(match);
}
을 대신를 사용
matches.push(match[1]);
당신은 필요 String.match
대신 exec
를 사용
'%name% some text %txt%'.match(reg);
좋아,'[ "TXT"을 "이름"]'이제 모두 답이 [ "%의 TXT의 %"를 "% 이름 %를"]''반환,하지만 어떻게에만 반환 ?? – clarkk
전체 일치 대신 캡처 된 그룹을 사용하십시오. –