返回 Javascript 中正则表达式 match() 的位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2295657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return positions of a regex match() in Javascript?
提问by stagas
Is there a way to retrieve the (starting) character positions inside a string of the results of a regex match() in Javascript?
有没有办法在 Javascript 中检索正则表达式 match() 结果字符串中的(起始)字符位置?
采纳答案by stagas
Here's what I came up with:
这是我想出的:
// 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);
}
回答by Gumbo
execreturns an object with a indexproperty:
exec返回一个具有index属性的对象:
var match = /bar/.exec("foobar");
if (match) {
console.log("match found at " + match.index);
}
And for multiple matches:
对于多个匹配项:
var re = /bar/g,
str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
console.log("match found at " + match.index);
}
回答by Jimbo Jonny
From developer.mozilla.orgdocs on the String .match()method:
来自developer.mozilla.org文档关于 String.match()方法:
The returned Array has an extra input property, which contains the original string that was parsed. In addition, it has an index property, which represents the zero-based index of the match in the string.
返回的 Array 有一个额外的 input 属性,它包含被解析的原始字符串。此外,它还有一个 index 属性,表示 string 中匹配项的从零开始的索引。
When dealing with a non-global regex (i.e., no gflag on your regex), the value returned by .match()has an indexproperty...all you have to do is access it.
在处理非全局正则表达式(即,g正则表达式上没有标志)时,返回的值.match()有一个index属性……您所要做的就是访问它。
var index = str.match(/regex/).index;
Here is an example showing it working as well:
这是一个显示它也可以工作的示例:
var str = 'my string here';
var index = str.match(/here/).index;
alert(index); // <- 10
I have successfully tested this all the way back to IE5.
我已经成功地测试了这一点,一直回到 IE5。
回答by felipeab
Here is a cool feature I discovered recently, I tried this on the console and it seems to work:
这是我最近发现的一个很酷的功能,我在控制台上尝试过,它似乎有效:
var text = "border-bottom-left-radius";
var newText = text.replace(/-/g,function(match, index){
return " " + index + " ";
});
Which returned: "border 6 bottom 13 left 18 radius"
其中返回:“border 6 bottom 13 left 18 radius”
So this seems to be what you are looking for.
所以这似乎是你正在寻找的。
回答by Jimmy Cuadra
You can use the searchmethod of the Stringobject. This will only work for the first match, but will otherwise do what you describe. For example:
您可以使用对象的search方法String。这仅适用于第一场比赛,否则将按照您的描述进行。例如:
"How are you?".search(/are/);
// 4
回答by Sandro Rosa
This member fn returns an array of 0-based positions, if any, of the input word inside the String object
此成员 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 ;
}
Now try
现在试试
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 ) );
You can also input regular expressions:
您还可以输入正则表达式:
var _second = "z^2+2z-1" ;
console.log( _second.matching_positions( "[0-9]\z+", 0, 0, 0 ) );
Here one gets the position index of linear term.
这里得到线性项的位置索引。
回答by Yaroslav
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));
回答by SwiftNinjaPro
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
or
或者
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

