javascript - 正则表达式匹配星号、波浪线、破折号和方括号
问题描述
我一直在尝试编写一个正则表达式来匹配星号、波浪号、破折号和方括号。
我有的:
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);
});
推荐阅读
- vue.js - 即使使用 set,Vue 也不会重新渲染列表
- flutter - 日文日期的格式
- asp.net - 正则表达式,包含特定的单词
- r - R:如何对数据进行分组并在数据框中的不同组内分配因子级别?
- sql - SQL 连接 - 忽略空值 - 结果不应包含空格
- react-leaflet - React-Leaflet Map 的 Z-Index
- sql - 如何将以下一组查询的输出转换为 SQL Server 中的视图?
- sql - SQL 不接受正字符串
- tsql - TSql SqlParameters - 非法值或排序规则问题?
- three.js - Three.js r125 BufferGeometry `vertices` 不存在