获取字符串中的所有匹配项

获取字符串中的所有匹配项

本文介绍了JavaScript regex 获取字符串中的所有匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取字符串中的匹配数组.目前,我的字符串是媒体查询.我删除了媒体查询中的所有新行,因此一个媒体查询可能如下所示:

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}"]

这是我的尝试:

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

我假设 match 会给我所有匹配.但是我只得到了一场比赛,所以我一定是做错了什么.

I was under the assumption match would give me all matches. However I am only getting one match, so I must be doing something wrong.

推荐答案

你需要使用 g (for global) identifier as in

You need to use g (for global) identifier as in

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

查看文档这里.此外,正如@chiliNUT 在评论中提到的,您需要使用 .*? 而不是 .* 以使您的正则表达式不贪婪.请参阅此处了解更多信息.

See the documentation here. Also, as mentioned in the comments by @chiliNUT, you need to use .*? instead of .* in order for your regex not be greedy. See here for more.

这篇关于JavaScript regex 获取字符串中的所有匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 18:43