有一串字符串: '<span class="className">111</span><span class="className">222</span><span class="className">333</span>'
固定格式是'<span class="className">abc</span>'
其中abc可能会有[,\,{ 之类的特殊字符,现在想要匹配111,222,333,abc,该如何获取
const reg = new RegExp('<span class="className">(.+?)</span>', 'g');
str = str.replace(reg, word=>{
const newReg = new RegExp(keyword,'g')
replace(newReg, `<span style="color:red;">${keyword}</span>`)
})
这样匹配到的都是完整的字符串,但是我只想要标签之间的内容,并且在标签之间的内容中还要进行二次匹配,匹配某个关键字
你想要的标签之间的内容,是指 111,222,333,abc 这样的吗?
let reg = /<span class="className">(\d+)/g
let ans = []
let matched = null
while ((matched = reg.exec(str)) !== null) {
ans.push(matched[1]);
}
使用正则表达式的exec方法可以匹配字符串中的一段特定文本,并且返回一个匹配结果数组,其中包括匹配到的文本及相关索引位置等信息。要获取该文本的中间内容,可以使用数组的索引位置信息进行截取。具体步骤如下:
const regex = /world/;
const matchArray = regex.exec("hello world!");
if (matchArray && matchArray.length > 1) {
// 匹配成功,执行下一步操作
} else {
// 匹配失败
}
const middleText = "hello world!".substring(matchArray.index, matchArray.index + matchArray[0].length);
其中,matchArray.index表示匹配到的文本在原字符串中的起始位置,matchArray[0].length表示匹配到的文本的长度。
完整代码示例:
const regex = /world/;
const matchArray = regex.exec("hello world!");
if (matchArray && matchArray.length > 1) {
const middleText = "hello world!".substring(matchArray.index, matchArray.index + matchArray[0].length);
console.log(middleText); // 输出:world
} else {
console.log('匹配失败');
}