[javascript] Javascript에서 정규 표현식 match ()의 위치를 ​​반환합니까?

Javascript에서 정규 표현식 match () 결과 문자열에서 (시작) 문자 위치를 검색하는 방법이 있습니까?



답변

execindex속성이 있는 객체를 반환합니다 .

var match = /bar/.exec("foobar");
if (match) {
    console.log("match found at " + match.index);
}

그리고 여러 경기에서 :

var re = /bar/g,
    str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
    console.log("match found at " + match.index);
}


답변

내가 생각해 낸 것은 다음과 같습니다.

// Finds starting and ending positions of quoted text
// in double or single quotes with escape char support like \" \'
var str = "this is a \"quoted\" string as you can 'read'";

var patt = /'((?:\\.|[^'])*)'|"((?:\\.|[^"])*)"/igm;

while (match = patt.exec(str)) {
  console.log(match.index + ' ' + patt.lastIndex);
}


답변

에서 developer.mozilla.org 문자열에 문서 .match()방법 :

반환 된 Array에는 구문 분석 된 원래 문자열이 포함 된 추가 입력 속성이 있습니다. 또한 index 속성이 있으며, 이는 문자열에서 일치 항목의 인덱스 (0부터 시작)를 나타냅니다 .

비전 역 정규 표현식을 처리 할 때 (즉, 정규 표현식에 g플래그가 없는 경우 )에 의해 반환 된 값 .match()에는 index속성이 있습니다 … 액세스하면됩니다.

var index = str.match(/regex/).index;

다음은 잘 작동하는 예입니다.

var str = 'my string here';

var index = str.match(/here/).index;

alert(index); // <- 10

IE5까지 이것을 성공적으로 테스트했습니다.


답변

객체 의 search방법을 사용할 수 있습니다 String. 이것은 첫 번째 경기에서만 작동하지만 다른 방법으로 설명합니다. 예를 들면 다음과 같습니다.

"How are you?".search(/are/);
// 4


답변

최근에 내가 발견 한 멋진 기능이 콘솔에서 시도했지만 작동하는 것 같습니다.

var text = "border-bottom-left-radius";

var newText = text.replace(/-/g,function(match, index){
    return " " + index + " ";
});

“반경 6 하단 13 왼쪽 18 반경”

그래서 이것은 당신이 찾고있는 것 같습니다.


답변

최신 브라우저에서는 string.matchAll ()으로 이를 수행 할 수 있습니다 .

이 접근 방식의 장점 RegExp.exec()@Gumbo의 답변 에서처럼 정규식이 상태 저장에 의존하지 않는다는 입니다.

let regexp = /bar/g;
let str = 'foobarfoobar';

let matches = [...str.matchAll(regexp)];
matches.forEach((match) => {
    console.log("match found at " + match.index);
});


답변

이 멤버 fn은 String 객체 내부의 입력 단어에 대한 0 기반 위치의 배열을 반환합니다 (있는 경우).

String.prototype.matching_positions = function( _word, _case_sensitive, _whole_words, _multiline )
{
   /*besides '_word' param, others are flags (0|1)*/
   var _match_pattern = "g"+(_case_sensitive?"i":"")+(_multiline?"m":"") ;
   var _bound = _whole_words ? "\\b" : "" ;
   var _re = new RegExp( _bound+_word+_bound, _match_pattern );
   var _pos = [], _chunk, _index = 0 ;

   while( true )
   {
      _chunk = _re.exec( this ) ;
      if ( _chunk == null ) break ;
      _pos.push( _chunk['index'] ) ;
      _re.lastIndex = _chunk['index']+1 ;
   }

   return _pos ;
}

이제 시도

var _sentence = "What do doers want ? What do doers need ?" ;
var _word = "do" ;
console.log( _sentence.matching_positions( _word, 1, 0, 0 ) );
console.log( _sentence.matching_positions( _word, 1, 1, 0 ) );

정규식을 입력 할 수도 있습니다.

var _second = "z^2+2z-1" ;
console.log( _second.matching_positions( "[0-9]\z+", 0, 0, 0 ) );

여기서는 선형 항의 위치 인덱스를 얻습니다.