user7203701
user7203701

Reputation: 65

Regular expression match either of the words or both as comma separated

I have an input that can be either public or internal or comma separated public and internal in any order. Following are the all possible scenarios:

public

internal

public,internal

internal,public

To check if it's either public or internal I'm using the following regex:

(?:public|internal)

To check if they are comma separated and in any order, I'm using the following regex:

(?=.*public)(?=.*internal)

I'm having hard time merging these two regex-s together.

Thanks in advance

Upvotes: 1

Views: 117

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Use the following regex pattern:

(^public$|^internal$)|(^public,internal$|internal,public$)

https://regex101.com/r/TSvqCX/1

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

Since there are only four options, it is easy to match all four possibilities:

public|internal|public,internal|internal,public

You can use optional matching to "fold" four possible matches into two expressions:

public(?:,internal)?|internal(?:,public)?

Upvotes: 2

Related Questions