是否有一种方法来检索(开始)字符的位置在一个正则匹配()在Javascript的结果字符串?
当前回答
在现代浏览器中,您可以使用string.matchAll()来实现这一点。
与RegExp.exec()相比,这种方法的优点是它不依赖于正则表达式是有状态的,就像@Gumbo的答案中那样。
让regexp = /bar/g; 让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 ) );
这里我们得到了线性项的位置指标。
在现代浏览器中,您可以使用string.matchAll()来实现这一点。
与RegExp.exec()相比,这种方法的优点是它不依赖于正则表达式是有状态的,就像@Gumbo的答案中那样。
让regexp = /bar/g; 让STR = 'foobarfoobar'; let matches =[…str.matchAll(regexp)]; matches.forEach((match) => { Console.log ("match found at " + match.index); });
我很幸运地使用了这个基于matchAll的单行解决方案(我的用例需要一个字符串位置数组)
let regexp = /bar/g;
let str = 'foobarfoobar';
let matchIndices = Array.from(str.matchAll(regexp)).map(x => x.index);
console.log(matchIndices)
输出:[3,9]
Exec返回一个带有index属性的对象:
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); }
您可以使用String对象的搜索方法。这将只适用于第一个匹配,但在其他情况下将完成您所描述的工作。例如:
"How are you?".search(/are/);
// 4