我一直在尝试编写一个正则表达式来匹配星号、波浪号、破折号和方括号。
我有什么:
const str = "The] quick [brown] fox **jumps** over ~~the~~ lazy dog --- in the [woods";
console.log(str.match(/[^\]][^\[\]]*\]?|\]/g));
// [
// "The]",
// " quick ",
// "[brown]",
// " fox **jumps** over ~~the~~ lazy dog --- in the ",
// "[woods"
// ];
我想要的:
[
"The]",
" quick ",
"[brown]",
" fox ",
"**jumps**",
" over ",
"~~the~~",
" lazy dog ",
"---",
" in the ",
"[woods"
];
编辑:
字符串的更多示例/组合是:
"The] quick brown fox jumps [over] the lazy [dog"
// [ "The]", " quick brown fox jumps ", "[over]", " the lazy ", "[dog" ]
"The~~ quick brown fox jumps [over] the lazy **dog"
// [ "The~~", " quick brown fox jumps ", "[over]", " the lazy ", "**dog" ]
编辑 2:
我知道这很疯狂但是:
"The special~~ quick brown fox jumps [over the] lazy **dog on** a **Sunday night."
// [ "The special~~", " quick brown fox jumps ", "[over the]", " lazy ", "**dog on**", " a ", "**Sunday night" ]
最佳答案
您可以使用此正则表达式进行更多替换以包含您想要的匹配项:
const re = /\[[^\[\]\n]*\]|\b\w+\]|\[\w+|\*\*.+?(?:\*\*|$)|-+|(?:^|~~).+?~~|[\w ]+/mg;
const arr = [
'The special~~ quick brown fox jumps [over the] lazy **dog on** a **Sunday night.',
'The] quick brown fox jumps [over] the lazy [dog',
'The] quick [brown] fox **jumps** over ~~the~~ lazy dog --- in the [woods'
];
var n;
arr.forEach( str => {
m = str.match(re);
console.log(m);
});
关于javascript - 用于匹配星号、波浪号、破折号和方括号的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57914609/