简体   繁体   English

正则表达式匹配-方括号内的内容

[英]Regex Matching - Content within brackets

This is a fast question, I just don't know many Regex tricks and can't find documentation for this exact point: 这是一个快速的问题,我只是不知道许多正则表达式的技巧,也找不到关于这一点的文档:

Lets say I have the string: 可以说我有字符串:

'I know [foo] and [bar] about Regex'

I want to do a JS Regex pattern that makes an array of each bracket encapsulation. 我想做一个JS Regex模式,使每个括号封装组成一个数组。 Result: 结果:

['[foo]', '[bar]']

I currently have: 我目前有:

str.match(/\[(.*)\]/g);

But this returns: 但这返回:

'[foo] and [bar]'

Thanks. 谢谢。

str.match(/\[(.*?)\]/g);

Use a ? 使用? modifier to make the * quantifier non-greedy. 使*量词为非贪婪的修饰符。 A non-greedy quantifier will match the shortest string possible rather than the longest, which is the default. 非贪婪的量词将匹配可能的最短字符串,而不是最长的字符串,这是默认设置。

Use this instead: 使用此代替:

var str = 'I know [foo] and [bar] about Regex';
str.match(/\[([^\[\]]*)\]/g);

Your regex is partially wrong because of (.*) , which makes your pattern to allow any character between [ and ] , which includes [ and ] . 由于(.*) ,您的正则表达式部分错误,这使您的模式允许[]之间的任何字符,包括[]

尝试

var array = 'I know [foo] and [bar] about Regex'.match(/(\[[^\]]+\])/g)

Use this instead: 使用此代替:

\\[[^\\]]+\\]

Your regex is partially wrong because of (.*) , which makes your pattern to allow any character between [ and ] , which includes [ and ] . 由于(.*) ,您的正则表达式部分错误,这使您的模式允许[]之间的任何字符,包括[]

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

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