简体   繁体   English

JavaScript正则表达式以字符串形式获取所有匹配项

[英]JavaScript regex get all matches in a string

I want to get an array of matches within a string. 我想在字符串中获取匹配项数组。 Currently, my string is a media query. 目前,我的字符串是媒体查询。 I removed all new lines in the media query, so one media query might look like this: 我删除了媒体查询中的所有新行,因此一个媒体查询可能如下所示:

@media (max-width: 1200px) { .container { padding-left: 0px; } .bundles {padding-right:10px} }

What I want to do is get all the classes from the media query including their style attributes. 我要做的是从媒体查询中获取所有类,包括其样式属性。 So I would like an array that look as follows: 所以我想要一个看起来如下的数组:

[".container { padding-left: 0px; }", ".bundles {padding-right:10px}"]

This is my attempt: 这是我的尝试:

var identifiers = mediaQuery.match(/\.(.*)}/);

I was under the assumption match would give me all matches. 我当时以为match会给我所有比赛。 However I am only getting one match, so I must be doing something wrong. 但是我只有一场比赛,所以我一定做错了。

Try this: 尝试这个:

/\.\w+\s*\{[^\}]+\}/

Note that it will find only simple classes, and not ids or any complex css selectors. 请注意,它将仅找到简单的类,而不找到id或任何复杂的CSS选择器。 Since you wrote classes in your question, the regex should be fine. 由于您在问题中编写了类,因此正则表达式应该没问题。 If you need more complex matches, then improve your question ans I'll improve my answer :) 如果您需要更复杂的比赛,那么请改善您的问题,我将改善我的答案:)

You need to use g (for global) identifier as in 您需要使用g (用于全局)标识符,如下所示

var identifiers = mediaQuery.match(/\.(.*?)}/g);

See the documentation here . 请参阅此处的文档。 Also, as mentioned in the comments by @chiliNUT, you need to use .*? 另外,如@chiliNUT的注释中所述,您需要使用.*? instead of .* in order for your regex not be greedy. 而不是.* ,以便您的正则表达式不贪婪。 See here for more. 看到这里更多。

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

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