简体   繁体   English

Javascript和Regex,倍数匹配

[英]Javascript & Regex, multiples matches

I have a quick question for you (for you, I've personally spent hours on this). 我有一个简短的问题(对你而言,我个人花了好几个小时)。 I've created a web application in Javascript/Jquery to validate a CSS stylesheet. 我在Javascript / Jquery中创建了一个Web应用程序来验证CSS样式表。

I need to extract multiple CSS class names from a selector with Regex. 我需要从Regex的选择器中提取多个CSS类名。 I've done something like: 我做过类似的事情:

var selector = this.value;
var userNewClass = selector.match(/[.]([A-Za-z_-]*)/);
alert(userNewClass.toString());

It's almost working, but I have two issues with the code (you have a Regex noob here). 它几乎正常工作,但我有两个代码问题(你有一个正则表达式noob)。 If I write something like: 如果我写的东西如下:

.test:hover

It returns me 它归还给我

.test, test 

The same class name but on with the dot and the other without the dot. 相同的类名,但带有点,另一个没有点。 If I write a selector with multiple class name: 如果我编写一个具有多个类名的选择器:

.test, .hello

I'm getting the same result...Is there anyway to modify my Regex (or my code ?) to obtain all the classes names with the dot (.) only, considering the user can have a unlimited number of classes in the same selector? 我得到了相同的结果......无论如何都要修改我的正则表达式(或我的代码?)以获得所有带有点(。)的类名,考虑到用户可以在同一个类中拥有无限数量的类选择?

.test is the full match, test is the captured group (anything in parens () ). .test是完全匹配, test是捕获的组(parens ()任何内容)。 You also need to add a g at the end after the closing / to match every instance and not just the first one. 您还需要添加一个g末闭幕后/每一个实例,而不只是第一个匹配。

That said, you likely don't need regex for this and might be better served using split on the string. 也就是说,你可能不需要正则表达式,并且可能更好地使用字符串上的split服务。

'.test, .hello'.split(', ') // returns an array ['.test', '.hello']

If you absolutely must use regex, try this: 如果你绝对必须使用正则表达式,试试这个:

/\.(\w+)/g

This will match (and capture) any and all sequences of one or more letters and/or numbers \\w+ which follow a literal . 这将匹配(并捕获)跟随文字的一个或多个字母和/或数字\\w+任何和所有序列.

You will have to use the RegExp.exec method: 您将不得不使用RegExp.exec方法:

var input = ".test1.test2 .test3, .test4";

var re = /\.[\w\-]+/ig, match, matches = [];

while (match = re.exec(input)) {
  matches.push(match[0]);
}

alert(matches);

Using split will not work, as you will have to parse out pseudo classes and all other possible CSS syntax elements. 使用split将无法工作,因为您必须解析伪类和所有其他可能的CSS语法元素。

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

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