简体   繁体   中英

Regex pattern matching string iff it only contain certain allowed characters

I am new to regrex and trying to get a grasp of it.

How could I write a regrex string that matches a string if and only if the string contains only certain allowed characters, let's say capital 'A', 'B', 'C', 'D' and 'E', ei it should match 'A', 'ABC', 'CEA', 'ABCEACBBCAED?, but not 'AGV' AcD', 'a', etc. (?)

re.search(some_regex_string, some_string)

You need to use this regex for matching the kind of sample data in your post.

^[A-E]+$

Regex Demo

In case you have a larger string where you want to only match tokens which has only A to Z characters, then in that case you can use word boundaries around the regex as this,

\b[A-E]+\b

Which will match only strings that contain A to E characters into the string.

Demo for matching intended strings in a larger string

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