简体   繁体   English

如何拆分正则表达式匹配

[英]How to split regex matches

I would like to match all given ( and ) in a string, but I'm having trouble because of my current solution matches () while my intention is got a split result like ['(',')']我想在一个字符串中匹配所有给定的() ,但是由于我当前的解决方案匹配()而我的意图是得到像['(',')']这样的拆分结果,所以我遇到了麻烦

My regex expression is: /[()]+/g , Regex101 playground .我的regex表达式是: /[()]+/g , Regex101 playground

How can I manage to get the desired behavior only with a regex expression?如何仅使用正则表达式才能获得所需的行为?

 const matchType = str => str.match(/[()]+/g) console.log(matchType('{(})[]')); // ['(',')] // Expected ['(',')'] console.log(matchType('{[()]}')); // ['()']

Do not use quantifier + ,不要使用量词+ ,

when you use + quantifier + it means one or more time,当你使用+量词+时,它表示一个或多个时间,

[()]+ this means match ( or ) one or more time, so when you have string like () it consider it as a single match [()]+这意味着匹配( or )一次或多次,因此当您有类似()的字符串时,它会将其视为单个匹配

 const matchType = str => str.match(/[()]/g) console.log(matchType('{(})[]')); // ['(',')] // Expected ['(',')'] console.log(matchType('{[()]}'));

You just need to get rid of the + :你只需要摆脱+

const matchType = str => str.match(/[()]/g)

The + means that you will match on one or more parens. +表示您将匹配一个或多个括号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何拆分正则表达式空间和标点符号匹配,但将标点符号保留在结果数组中? - How to split regex space and punctuation matches, but keep the punctuation in the resulting array? 如何使用正则表达式以开始字符分隔字符串匹配以下任何&lt;= | &gt; = | = | != - How to split a string using regex with beginning character matches any of this <= | >= | = | != JavaScript正则表达式:如何将Regex子表达式匹配分割为多维字符串数组? - JavaScript Regex: How to split Regex subexpression matches in to multi-dimensional string arrays? 使用 javascript 如何遍历正则表达式匹配并将字符串拆分为由超链接划分的片段数组? - Using javascript how can I loop through regex matches and split string into array of pieces divided by hyperlinks? 如何创建仅匹配1或2的正则表达式 - How to create Regex that matches only 1 or 2 正则表达式:如何返回不在括号中的匹配项 - Regex: How to return matches that are not in the bracket 如何用jQuery突出显示RegEx匹配? - How to highlight RegEx matches with jQuery? Javascript - 如果下一个字符不是,则使用正则表达式拆分以返回所有匹配项 - Javascript - .split with Regex to Return All Matches If Next Character Is Not 具有三个匹配项的JS split()正则表达式与单个结果数组 - JS split() Regex with Three Matches to a single Results Array 如何在javascript中使用正则表达式拆分? - How to split with regex in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM