简体   繁体   中英

Regex match any of the words separated by slashes

I need to develop a validation pattern for catching any kind from:

pdf/csv/xlsx

select any separate word is simple:

(pdf|csv|xlsx).

However, I need to check that any combination with them separated by slash is fine as well.

For example, correct flow :

pdf/csv/xlsx
pdf
pdf/csv
csv/xlsx
xlsx
pdf/xlsx

Incorrect :

test
incorrect
doc

You may use this regex:

^(?:pdf|csv|xlsx?)(?:/(?:pdf|csv|xlsx?))*$

RegEx Demo

How about this?

^(pdf|csv|xlsx)(\/(pdf|csv|xlsx))*$

This idea makes the pattern a bit shorter:

^(?:(?:pdf|csv|xlsx?)/?\b)+$

Here is a demo at regex101

The slash is set to optional here and the word boundary \b requires it between words on the one hand and disallows it at the end on the other. It might be a tiny bit less efficient, but looks cool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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