Подтвердить что ты не робот

Вернуть позиции регулярного выражения match() в Javascript?

Есть ли способ получить начальные позиции символа внутри строки результатов регулярного выражения() в Javascript?

4b9b3361

Ответ 1

Вот что я придумал:

// 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);
}

Ответ 2

exec возвращает объект со свойством index:

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

И для нескольких совпадений:

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

Ответ 3

Из developer.mozilla.org docs в методе String .match():

Возвращенный массив имеет дополнительное свойство ввода, которое содержит оригинальная строка, которая была проанализирована. Кроме того, имеет индекс свойство, которое представляет нулевой индекс совпадения в строка.

При работе с неглобальным регулярным выражением (т.е. флажком g в вашем регулярном выражении) значение, возвращаемое .match(), имеет свойство index... все, что вам нужно сделать, это получить к нему доступ.

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

Вот пример, показывающий, что он работает:

var str = 'my string here';

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

alert(index); // <- 10

Ответ 4

Вы можете использовать метод search объекта String. Это будет работать только для первого матча, но в противном случае будет делать то, что вы описываете. Например:

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

Ответ 5

Вот замечательная функция, которую я недавно обнаружил, я попробовал это на консоли и, похоже, работает:

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

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

Что вернулось: "border 6 bottom 13 left 18 radius"

Итак, это похоже на то, что вы ищете.

Ответ 6

Этот член fn возвращает массив позиций 0, если они есть, входного слова внутри объекта String

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

Здесь получается индекс положения линейного члена.

Ответ 7

var str = "The rain in SPAIN stays mainly in the plain";

function searchIndex(str, searchValue, isCaseSensitive) {
  var modifiers = isCaseSensitive ? 'gi' : 'g';
  var regExpValue = new RegExp(searchValue, modifiers);
  var matches = [];
  var startIndex = 0;
  var arr = str.match(regExpValue);

  [].forEach.call(arr, function(element) {
    startIndex = str.indexOf(element, startIndex);
    matches.push(startIndex++);
  });

  return matches;
}

console.log(searchIndex(str, 'ain', true));