简体   繁体   English

正则表达式在JavaScript中拉出方括号

[英]Regex to pull out square brackets in javascript

Given... 鉴于...

var parts = 'value[1]'.split(/\[\]/);

What is the regex to have... 有什么正则表达式...

parts[0] === 'value';
parts[1] === '1';

The regex I have above doesn't work. 我上面的正则表达式不起作用。

Your regex is matching only when '[' is followed by ']'. 仅当'['后跟']'时,您的正则表达式才匹配。 You want to use an "or": 您要使用“或”:

var parts = 'value[1]'.split(/\[|\]/);

Tip: I use https://regex101.com/ which is very good to explain what the regex is matching in detail. 提示:我使用https://regex101.com/很好地解释了正则表达式详细匹配的内容。 Or, for .NET: http://regexstorm.net/tester 或者,对于.NET: http : //regexstorm.net/tester

I would suggest using match for this: 我建议为此使用match

match = 'value[1]'.match(/(\w+)\[(\d+)\]/)
match[1] // "value"
match[2] // "1"

The match here will match any word characters ( \\w+ ), followed by a [ , then any number of digits ( \\d+ ), followed by a ] . 此处的匹配项将匹配任何单词字符( \\w+ ),后跟[ ,然后是任意数字位数( \\d+ ),然后是]

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM