sta*_*gas 128 javascript regex match string-matching
有没有办法在Javascript中检索正则表达式匹配()的结果字符串中的(起始)字符位置?
Gum*_*mbo 191
exec返回具有index属性的对象:
var match = /bar/.exec("foobar");
if (match) {
console.log("match found at " + match.index);
}Run Code Online (Sandbox Code Playgroud)
对于多场比赛:
var re = /bar/g,
str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
console.log("match found at " + match.index);
}Run Code Online (Sandbox Code Playgroud)
sta*_*gas 57
这是我想出的:
// 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);
}Run Code Online (Sandbox Code Playgroud)
bri*_*uth 17
在现代浏览器中,您可以使用string.matchAll()完成此操作。
这种方法 vs 的好处RegExp.exec()是它不依赖于有状态的正则表达式,如@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);
});Run Code Online (Sandbox Code Playgroud)
Jim*_*nny 13
来自关于String 方法的developer.mozilla.org文档.match():
返回的Array有一个额外的input属性,它包含已解析的原始字符串.此外,它还有一个index属性,表示字符串中匹配的从零开始的索引.
处理非全局正则表达式(即正则表达式中没有g标志)时,返回的值.match()有一个index属性......您所要做的就是访问它.
var index = str.match(/regex/).index;
Run Code Online (Sandbox Code Playgroud)
以下示例显示了它的工作原理:
var str = 'my string here';
var index = str.match(/here/).index;
alert(index); // <- 10Run Code Online (Sandbox Code Playgroud)
我已成功测试了这一回到IE5.
您可以使用search该String对象的方法.这仅适用于第一场比赛,否则将按照您的描述进行.例如:
"How are you?".search(/are/);
// 4
Run Code Online (Sandbox Code Playgroud)
小智 5
这是我最近发现的一个很酷的功能,我在控制台上尝试了一下,它似乎可以正常工作:
var text = "border-bottom-left-radius";
var newText = text.replace(/-/g,function(match, index){
return " " + index + " ";
});
Run Code Online (Sandbox Code Playgroud)
其中返回:“边界6底13左18半径”
所以这似乎是您想要的。
| 归档时间: |
|
| 查看次数: |
95163 次 |
| 最近记录: |