Zwraca pozycje regex match () w Javascript?

Czy istnieje sposób, aby odzyskać (początkowe) pozycje znaków wewnątrz ciągu wyników regex match () w Javascript?

Author: stagas, 2010-02-19

10 answers

exec zwraca obiekt z właściwością index:

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

I dla wielu meczów:

var re = /bar/g,
    str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
    console.log("match found at " + match.index);
}
 247
Author: Gumbo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-16 15:15:07

Oto co wymyśliłem:

// 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);
}
 63
Author: stagas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-24 16:43:43

Z developer.mozilla.org docs on the String .match() method:

Zwrócona tablica ma dodatkową właściwość input, która zawiera oryginalny ciąg, który został przetworzony. Ponadto posiada indeks właściwość, która reprezentuje indeks dopasowania od zera w string .

Gdy mamy do czynienia z nie-globalnym regexem (tj. bez znacznika g na Twoim regex), wartość zwracana przez .match() ma właściwość index...wszystko, co musisz zrobić, to uzyskać dostęp to.

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

Oto przykład pokazujący, że działa również:

var str = 'my string here';

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

alert(index); // <- 10

Pomyślnie przetestowałem to aż do IE5.

 16
Author: Jimbo Jonny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-24 16:20:11

W nowoczesnych przeglądarkach można to osiągnąć za pomocą string.matchAll () .

Zaletą tego podejścia vs RegExp.exec() jest to, że nie polega ono na tym, że regex jest stateful, jak w @Gumbo ' s answer.

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

let matches = [...str.matchAll(regexp)];
matches.forEach((match) => {
    console.log("match found at " + match.index);
});
 10
Author: brismuth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-09 21:50:25

Możesz użyć metody search obiektu String. Będzie to działać tylko w pierwszym meczu, ale w przeciwnym razie zrobi to, co opisałeś. Na przykład:

"How are you?".search(/are/);
// 4
 8
Author: Jimmy Cuadra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-19 10:51:37

Oto fajna funkcja, którą odkryłem niedawno, próbowałem tego na konsoli i wydaje się działać:

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

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

Które zwróciło: "border 6 bottom 13 left 18"

Więc to wygląda na to, czego szukasz.
 6
Author: felipeab,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-30 13:39:25

Ten element fn zwraca tablicę pozycji słowa wejściowego wewnątrz obiektu 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 ;
}

Teraz spróbuj

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

Możesz również wprowadzić wyrażenia regularne:

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

Tutaj dostaje się indeks pozycji terminu liniowego.

 1
Author: Sandro Rosa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-29 14:20:01
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));
 1
Author: Yaroslav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-27 11:17:13

var str = 'my string here';

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

alert(index); // <- 10
 0
Author: Thomas FONTAINE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-22 12:53:03
function trimRegex(str, regex){
    return str.substr(str.match(regex).index).split('').reverse().join('').substr(str.match(regex).index).split('').reverse().join('');
}

let test = '||ab||cd||';
trimRegex(test, /[^|]/);
console.log(test); //output: ab||cd

Lub

function trimChar(str, trim, req){
    let regex = new RegExp('[^'+trim+']');
    return str.substr(str.match(regex).index).split('').reverse().join('').substr(str.match(regex).index).split('').reverse().join('');
}

let test = '||ab||cd||';
trimChar(test, '|');
console.log(test); //output: ab||cd
 -1
Author: SwiftNinjaPro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-12 18:46:11