简体   繁体   中英

How to use 'OR' in regular expressions?

I want to have a regular expression that accepts these forms :

23456KW33C3

23456KW33

23456K

23456

23456W33C3

23456W33

I wrote these two regex

/(?i)^2\d{4}K?(M|(W33)(C3)?)?$/i

/(?i)^2\d{4}K?(M|(W33)|(W33C3))?$/i

They accepts all forms but not 23456KW33C3 !!!

I use it in if expression :

if (preg_match('/(?i)^2\d{4}K?(M|(W33)(C3)?)?$/i' ,$text))

What's wrong with them ?

You expression works fine, you might just want to remove the start and end chars and it would pass 23456KW33C3 too.

2\d{4}k?(m|(w33)(c3)?)?

This link helps you to modify/update your expressions as you wish.

在此处输入图片说明

I'm not quite sure what you would like to match. You might want to simplify your expression and reduce the restrictions that it has.


If you wish to write your expressions with OR, this expression shows how you might want to do so:

2\d{4}(k|)|(m|w33)|(c3)

You can add them in between the capturing groups that you have, to swipe your desired outputs from left to right. Then, if you wanted, after that you can add more boundaries.

在此处输入图片说明

RegEx Circuit

This link helps you to visualize your expressions:

在此处输入图片说明

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