我有一个正则表达式来搜索字符串。
new RegExp("\\b"+searchText+"\\b", "i")
我的字符串:
"You are likely to find [[children]] in [[a school]]"
"[[school]] is for [[learning]]"
我如何只搜索括号中的单词?
正则表达式应包含searchText作为函数参数。
答案 0 :(得分:4)
此RegEx将为您提供所需内容的基础知识
\[\[[^\]]*\]\]
\[\[
与两个起始括号匹配。方括号是RegEx中的特殊字符,因此必须使用\
[^\]]*
是一个否定的集合,它匹配一个或多个零个或多个字符,除了右括号。这与方括号之间的内容匹配。\]\]
与两个右括号匹配。这是您可以执行此操作的一个非常基本的示例:
let string = "You are likely to find [[children]] in [[a school]]<br>[[school]] is for [[learning]]";
string = string.replace(/\[\[[^\]]*\]\]/g, x => `<mark>${x}</mark>`);
document.body.innerHTML = string;
答案 1 :(得分:3)
您可以使用此正则表达式:
var str = `-- You are likely to find [[children]] in [[a school]]
-- [[school]] is for [[learning]]`;
var regex = /(?<=(\[\[))([\w\s]*)(?=(\]\]))/gm;
var match = str.match(regex);
console.log(match);
答案 2 :(得分:1)
const re = /(?<=\[\[)[^\]]+(?=]])/gm
const string = `-- You are likely to find [[children]] in [[a school]]
-- [[school]] is for [[learning]]`
console.log(string.match(re))
const replacement = {
children: 'adults',
'a school': 'a home',
school: 'home',
learning: 'rest',
}
console.log(string.split(/(?<=\[\[)[^\]]+(?=]])/).map((part, index) => part + (replacement[string.match(re)[index]] || '')).join(''))