简体   繁体   English

正则表达式使用和/或匹配类列表

[英]regex match list of classes using and/or

I'm trying to figure out how to match a set of specific classes - 我试图弄清楚如何匹配一组特定的类-

I want to match classes inline AND/OR a (set of) colors only, either on their own or 2 together: 我只想将inline和/或一组(一组) colors进行匹配,或者单独使用它们,或者将两种colors一起使用:

<span class="inline"> should match <span class="inline">应该匹配

<span class="green"> should match <span class="green">应该匹配

<span class="inline green"> should match <span class="inline green">应该匹配

<span class="blue inline"> should match <span class="blue inline">应该匹配

-- -

<span class="inline green blue"> should not match (no more than 2 classes) <span class="inline green blue">不一致 (不超过2级的类)

<span class="green blue"> should not match (two colors - doesn't have inline class) <span class="green blue"> 匹配(两种颜色-没有内联类)

I've got this at the moment but it's not working: 我现在有这个,但是不起作用:

regex /((inline)?(\\s|green|blue|red|yellow))/ regex /((inline)?(\\s|green|blue|red|yellow))/

Any suggestions? 有什么建议么? Many thanks 非常感谢

How about the following regex? 下面的正则表达式如何?

/^(?:inline|green|blue|red|yellow)(?:\s+(?:inline|green|blue|red|yellow))?$/

It breaks down as follows: 它分解如下:

  • ^ : Start of the class string ^ :类字符串的开头
  • (?:) : Non-capturing group. (?:) :非捕获组。 Allows you to group things together without creating a capturing group. 允许您将事物分组在一起而无需创建捕获组。 This makes things faster. 这使事情变得更快。
  • inline|green|blue|red|yellow : An enumeration of all your possible values inline|green|blue|red|yellow :所有可能值的枚举
  • \\s+ : One or more whitespace characters. \\s+ :一个或多个空格字符。 Just \\s by itself is a bit limiting, I think. 我认为,仅\\ s本身就有一定的局限性。
  • (?:\\s+(?:inline|green|blue|red|yellow))? : This makes everything after the first class name completely optional. :这使得第一个类名称之后的所有内容完全可选。

Edit : 编辑

As per nnnnnn's comment, I think my original regex is ill-suited for the job. 根据nnnnnn的评论,我认为我原来的正则表达式不适合该工作。 However, I think that the following regex should be okay: 但是,我认为以下正则表达式应该可以:

/^(?:inline(?:\s+(?:green|blue|red|yellow))?)|(?:green|blue|red|yellow(?:\s+inline)?)$/

Obviously, it's a lot more complicated, but that's why it might be best to simply split the className string of the element on \\s+ , count the number of elements in the resulting array, and then check each on individually. 显然,这要复杂得多,这就是为什么最好在\\s+上简单拆分元素的className字符串,计算结果数组中元素的数量,然后逐个检查每个元素。

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

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