为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

不负相思意 2021-10-14 16:50:21
我一直在尝试编写一个正则表达式来匹配星号、波浪号、破折号和方括号。我拥有的: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" ]
查看完整描述

2 回答

?
米脂

TA贡献1836条经验 获得超3个赞

您可以使用此正则表达式进行更多更改以包含您想要的匹配项:


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

});


查看完整回答
反对 回复 2021-10-14
?
心有法竹

TA贡献1866条经验 获得超5个赞

您可以使用此正则表达式来拆分字符串。它在分隔符(**,~~或[])之一与匹配的分隔符或字符串的开始/结束之间拆分文本上的字符串;或在一系列连字符 ( -) 上。它使用捕获组来确保正则表达式匹配的字符串出现在输出数组中:


((?:\*\*|^)[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; }


查看完整回答
反对 回复 2021-10-14
  • 2 回答
  • 0 关注
  • 827 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信