简体   繁体   English

javascript - 搜索(正则表达式),获取匹配字符串最后一个字符的 position

[英]javascript - search(regex), get position of the last character of the matched string

In javascript, the String.search() returns the position (character index) of the character at the start of the match when there are multiple characters . javascript中,当有多个字符时String.search()返回匹配开始的字符的position(字符索引)。 Meaning, for example, if you try to regex search cde in abcdefghij , it returns 2 (where c is at) and not 4 (where e is at).意思是,例如,如果您尝试在abcdefghij中使用正则表达式搜索cde ,它会返回2c所在的位置)而不是4e所在的位置)。 How do I do this?我该怎么做呢? I wouldn't just take the position, add by a fixed number, and you'll get the last character ( Position + 2 ), that won't work if the match have varying length match.我不会只取 position,加上一个固定的数字,你会得到最后一个字符 ( Position + 2 ),如果匹配有不同的长度匹配,那将不起作用。

Use match instead.改用match You can use a capture group to add the length of the match.您可以使用捕获组来添加匹配的长度。

const [, group, index] = "abcdfghij".match(/(cde?)/)

/* Make sure results are not undefined */

const lastIndex = index + (group.length - 1);

You could always create your own method.您始终可以创建自己的方法。

function indexLastCharacter(string, search_word) {
    let indexFirstCharacter = string.search(search_word);
    return indexFirstCharacter + search_word.length;
}

console.log(indexLastCharacter("abcdefghij", "cde"))
// -> 5

I found out that the lookbehind also works, like (?<=y).*$ will return a position after y .我发现 lookbehind 也有效,例如(?<=y).*$将在y之后返回 position。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用正则表达式替换匹配字符串的最后一个字符 - Replace last character of a matched string using regex Javascript 正则表达式 - 仅将一个字符添加到匹配的字符串 - Javascript Regex - add only a character to matched string JavaScript获取字符串在另一个字符串内的最后一个字符的位置 - JavaScript get the last character's position of the string inside the other string 正则表达式排除最后匹配的字符 - Regex exclude last matched character 如何使用正则表达式和Javascript获取字符串的第一个和最后一个字符 - how to get the first and the last character of a string using a Regex and Javascript 如何使用JavaScript替换字符串中的最后一个匹配字符 - How to replace last matched character in string using javascript 如果单词的第一个字符匹配,则在字符串列表中搜索任何出现的单词并突出显示匹配的单词。Javascript regex - Search a string for any occurence of a word in a list of strings and higlight matched word if first character of word matches.Javascript regex 获取javascript中插入符号位置之前的最后一个字符 - get last character before caret position in javascript Javascript RegEx全局字符串搜索下划线字符(_) - Javascript RegEx global string search for underscore character(_) 使用正则表达式获取Google搜索的最后一个关键字 - Get last keyword of a Google search with a Javascript regex
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM