首页 > 解决方案 > 正则表达式匹配星号、波浪线、破折号和方括号

问题描述

我一直在尝试编写一个正则表达式来匹配星号、波浪号、破折号和方括号。

我有的:

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" ]

标签: javascriptregex

解决方案


您可以将此正则表达式与更多替代项一起使用,以包含您想要的匹配项:

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);
});

正则表达式演示


推荐阅读