code

Javascript의 regex.exec ()가 항상 동일한 값을 반환하지 않는 이유는 무엇입니까?

codestyles 2020. 8. 23. 09:15
반응형

Javascript의 regex.exec ()가 항상 동일한 값을 반환하지 않는 이유는 무엇입니까? [복제]


Chrome 또는 Firebug 콘솔에서 :

reg = /ab/g
str = "abc"
reg.exec(str)
   ==> ["ab"]
reg.exec(str)
   ==> null
reg.exec(str)
   ==> ["ab"]
reg.exec(str)
   ==> null

exec는 어떻게 든 상태 저장이며 이전에 반환 된 내용에 따라 달라 집니까? 아니면 이것은 단지 버그입니까? 항상 그런 일이 일어나지 않습니다. 예를 들어, 위의 'str'이 "abc abc"이면 발생하지 않습니다.


JavaScript RegExp객체는 상태 저장입니다.

정규식이 전역일 때 동일한 정규식 개체에 대해 메서드를 호출하면 마지막 일치가 끝날 때까지 인덱스에서 시작됩니다.

더 이상 일치하는 항목이 없으면 색인이 0자동으로 재설정 됩니다.


수동으로 재설정하려면 lastIndex속성을 설정하십시오 .

reg.lastIndex = 0;

이것은 매우 유용한 기능이 될 수 있습니다. 원하는 경우 문자열의 어느 지점에서나 평가를 시작할 수 있고 루프에있는 경우 원하는 수의 일치 후에 중지 할 수 있습니다.


다음은 루프에서 정규식을 사용하는 일반적인 접근 방식을 보여줍니다. 루프 조건으로 할당을 수행하여 더 이상 일치 항목이 없을 때 exec반환 된다는 사실을 활용 null합니다.

var re = /foo_(\d+)/g,
    str = "text foo_123 more text foo_456 foo_789 end text",
    match,
    results = [];

while (match = re.exec(str))
    results.push(+match[1]);

데모 : http://jsfiddle.net/pPW8Y/


할당 배치가 마음에 들지 않으면 예를 들어 다음과 같이 루프를 재 작업 할 수 있습니다.

var re = /foo_(\d+)/g,
    str = "text foo_123 more text foo_456 foo_789 end text",
    match,
    results = [];

do {
    match = re.exec(str);
    if (match)
        results.push(+match[1]);
} while (match);

데모 : http://jsfiddle.net/pPW8Y/1/


에서 MDN 워드 프로세서 :

정규식에서 "g"플래그를 사용하는 경우 exec 메서드를 여러 번 사용하여 동일한 문자열에서 연속적인 일치 항목을 찾을 수 있습니다. 이렇게하면 검색은 정규식의 lastIndex 속성에 지정된 str의 하위 문자열에서 시작됩니다 (test는 lastIndex 속성도 진행 함).

g플래그를 사용하고 exec있으므로 마지막으로 일치하는 문자열에서 끝까지 (를 반환 null) 계속 한 다음 다시 시작합니다.


개인적으로 저는 다른 방법으로 str.match(reg)


여러 일치

정규식에 g플래그 (전역 일치)가 필요한 경우 lastIndex속성 을 사용하여 색인 (마지막 일치 위치)을 재설정해야 합니다.

reg.lastIndex = 0;

This is due to the fact that exec() will stop on each occurence so you can run again on the remaining part. This behavior also exists with test()) :

If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test will also advance the lastIndex property)

Single Match

When there is only one possible match, you can simply rewrite you regex by omitting the g flag, as the index will be automatically reset to 0.

참고URL : https://stackoverflow.com/questions/11477415/why-does-javascripts-regex-exec-not-always-return-the-same-value

반응형