[英]find end index of a regular expression search/match
如果我將string.match()與正則表達式一起使用,我將返回匹配的字符串,但不會返回匹配發生的原始字符串的索引。 如果我做string.search(),我得到索引,但我不一定知道字符串的匹配部分有多長。 有兩種方法可以做到,所以我可以在原始字符串中獲得匹配結束的索引嗎?
我想我可以一個接一個地做(下面),假設他們以不同的方式返回相同的結果,但這看起來很丑陋和低效,我懷疑有更好的方法。
var str = "Fear leads to anger. Anger leads to hate. Hate leads to suffering";
var rgx = /l[aeiou]+d/i;
var match = str.match(rgx);
if (match && match[0]) {
var i = str.search(rgx);
console.log ("end of match is at index " + (i+match[0].length));
}
.match
返回具有以下屬性的新數組:
index屬性設置為完整字符串S中匹配的子字符串的位置。
input屬性設置為S.
length屬性設置為n + 1。
0屬性設置為匹配的子字符串(即,在offset i包含和offset e exclusive之間的S部分)。
對於每個整數i,使得i> 0且i <= n,將名為ToString(i)的屬性設置為r的captures數組的第i個元素。
來自http://bclary.com/2004/11/07/#a-15.10.6.2
match.index
將提供您所需要的。
或者:
if (match && match[0]) {
console.log ("end of match is at index " + (str.indexOf(match[0]) + match[0].length));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.