Tim
Tim

Reputation: 7056

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:

 

<span class="inline"> should match

<span class="green"> should match

<span class="inline green"> should match

<span class="blue inline"> should match

 --

<span class="inline green blue"> should not match (no more than 2 classes)

<span class="green blue"> should not match (two colors - doesn't have inline class)

 

I've got this at the moment but it's not working:

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

Any suggestions? Many thanks

Upvotes: 0

Views: 67

Answers (1)

HartleySan
HartleySan

Reputation: 7810

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
  • \s+: One or more whitespace characters. Just \s by itself is a bit limiting, I think.
  • (?:\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. 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.

Upvotes: 1

Related Questions