[英]Regex to match commas that are not in an array (enclosed in square brackets)
[英]Regex to match asterisks, tildes, dashes and square brackets
我一直在尝试编写一个正则表达式来匹配星号,波浪号,破折号和方括号。
我有的:
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); });
您可以使用此正则表达式拆分字符串。 它在分隔符之一( **
, ~~
或[]
)与匹配的分隔符或字符串的开头/结尾之间分割文本上的字符串。 或连字号( -
)。 它使用捕获组来确保与正则表达式匹配的字符串出现在输出数组中:
((?:\*\*|^)[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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.