猿问

正则表达式匹配星号、波浪号、破折号和方括号

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


我拥有的:


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


不负相思意
浏览 828回答 2
2回答

米脂

您可以使用此正则表达式进行更多更改以包含您想要的匹配项: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);});

心有法竹

您可以使用此正则表达式来拆分字符串。它在分隔符(**,~~或[])之一与匹配的分隔符或字符串的开始/结束之间拆分文本上的字符串;或在一系列连字符 ( -) 上。它使用捕获组来确保正则表达式匹配的字符串出现在输出数组中:((?:\*\*|^)[A-Za-z. ]+(?:\*\*|$)|(?:~~|^)[A-Za-z. ]+(?:~~|$)|(?:\[|^)[A-Za-z. ]+(?:\]|$)|-+const re = /((?:\*\*|^)[A-Za-z. ]+(?:\*\*|$)|(?:~~|^)[A-Za-z. ]+(?:~~|$)|(?:\[|^)[A-Za-z. ]+(?:\]|$)|-+)/;const str = [  '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 special~~ quick brown fox jumps [over the] lazy **dog on** a **Sunday night.'];str.forEach(v => console.log(v.split(re).filter(Boolean)));.as-console-wrapper { max-height: 100% !important; top: 0; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答