UFO ET IT

JavaScript 정규식 및 하위 일치

ufoet 2020. 11. 11. 21:00
반응형

JavaScript 정규식 및 하위 일치


g수정자가 설정 되면 Javascript 하위 일치가 작동하지 않는 이유는 무엇 입니까?

var text = 'test test test test';

var result = text.match(/t(e)(s)t/);
// Result: ["test", "e", "s"]

위의 작품의 벌금, result[1]이다 "e"하고 result[2]있다 "s".

var result = text.match(/t(e)(s)t/g);
// Result: ["test", "test", "test", "test"]

위는 내 캡처 그룹을 무시합니다. 다음이 유일한 유효한 솔루션입니까?

var result = text.match(/test/g);
for (var i in result) {
    console.log(result[i].match(/t(e)(s)t/));
}
/* Result:
["test", "e", "s"]
["test", "e", "s"]
["test", "e", "s"]
["test", "e", "s"]
*/

편집하다:

10 년 후 이제이 작업을 수행 할 수 있음을 기쁘게 알려 드리기 위해 다시 돌아 왔습니다 (.matchAll이 사양에 추가되었습니다).

let result = [...text.matchAll(/t(e)(s)t/g)];

알다시피 전역 수정자가 설정된 경우 Stringmatch()함수를 사용하면 캡처 된 그룹이 반환되지 않습니다.

이 경우 RegExp개체 를 사용하고 해당 exec()함수를 호출 할 수 있습니다. Stringmatch()거의 동일 RegExp의 ' exec()이와 같은 경우를 제외하고 ... 기능. 글로벌 변경자를 지정하면, 정상적인 match()기능이있는 동안, 캡처 그룹을 반환하지 않습니다 RegExp'의 exec()기능을 것입니다. ( 여기 에 다른 곳에서 언급 됨 .)

기억해야 할 또 다른 점 exec()은 하나의 큰 배열로 일치 항목을 반환하지 않는다는 것 null입니다. 이 경우 일치 항목이 다 소모 될 때까지 계속 반환하며이 경우를 반환합니다 .

예를 들어 다음과 같이 할 수 있습니다.

var pattern = /t(e)(s)t/g;  // Alternatively, "new RegExp('t(e)(s)t', 'g');"
var match;    

while (match = pattern.exec(text)) {
    // Do something with the match (["test", "e", "s"]) here...
}

노트의 또 다른 일이 있다는 것입니다 RegExp.prototype.exec()RegExp.prototype.test()제공된 문자열에서 정규 표현식을 실행하고 첫 번째 결과를 반환합니다. 모든 순차 호출은 RegExp.prototype.lastIndex문자열의 현재 위치를 기반으로 업데이트되는 결과 집합을 단계별 로 수행합니다.

다음은 예입니다. // 예와 패턴에 4 개의 일치 항목이 있음을 기억하십시오. lastIndex는 0에서 시작합니다.

pattern.test(text); // pattern.lastIndex = 4
pattern.test(text); // pattern.lastIndex = 9
pattern.exec(text); // pattern.lastIndex = 14
pattern.exec(text); // pattern.lastIndex = 19

// if we were to call pattern.exec(text) again it would return null and reset the pattern.lastIndex to 0
while (var match = pattern.exec(text)) {
    // never gets run because we already traversed the string
    console.log(match);
}

pattern.test(text); // pattern.lastIndex = 4
pattern.test(text); // pattern.lastIndex = 9

// however we can reset the lastIndex and it will give us the ability to traverse the string from the start again or any specific position in the string
pattern.lastIndex = 0;

while (var match = pattern.exec(text)) {
    // outputs all matches
    console.log(match);
}

MDN에서RegExp 객체 를 사용하는 방법에 대한 정보를 찾을 수 있습니다 (특히 함수에 대한 문서는 여기 있습니다 ).exec()


10 년 전에 찾고 있던 답으로이 질문에 처음으로 답한 사람이 저라는 사실에 놀랐습니다 (답은 아직 존재하지 않았습니다). 나는 또한 실제 스펙 작성자가 나보다 먼저 대답하기를 바랐습니다.).

.matchAll has already been added to a few browsers.

In modern javascript we can now accomplish this by just doing the following.

let result = [...text.matchAll(/t(e)(s)t/g)];

.matchAll spec

.matchAll docs

I now maintain an isomorphic javascript library that helps with a lot of this type of string parsing. You can check it out here: string-saw. It assists in making .matchAll easier to use when using named capture groups.

An example would be

saw(text).matchAll(/t(e)(s)t/g)

Which outputs a more user-friendly array of matches, and if you want to get fancy you can throw in named capture groups and get an array of objects.

참고URL : https://stackoverflow.com/questions/844001/javascript-regular-expressions-and-sub-matches

반응형