javascript - 用于匹配星号、波浪号、破折号和方括号的正则表达式

标签 javascript regex

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

我有什么:

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

RegEx Demo

关于javascript - 用于匹配星号、波浪号、破折号和方括号的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57914609/

相关文章:

javascript - Spring Boot Web 静态资源

javascript - 正则表达式从文件中提取路径

javascript - 带有正则表达式的 JavaScript 中的第三个嵌套引用级别

regex - 为什么 MATLAB 的正则表达式只返回第一个匹配的标记字符串?

javascript - 重定向到在 angularjs 中不起作用的网页

Javascript,切换 setInterval

javascript - 如何将数百个 JS 对象属性放入数组中以用作 Chart.js 轴/数据

c++ - CPP 中正则表达式的问题

python - 如何在已通过正则表达式过滤的 pandas DataFrame 上使用 .apply 函数?

javascript - 如何访问渲染中构造函数中定义的 react native 变量?