Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to match specific combination of 2 letters with regex

given this set of letters

xx | af | an | bf | bn | cf | cn

how can I see if, given two characters, they match against one of the above?

I could easily hardcode the solution with a switch case, but I think regex is a more elegant solution.

like image 482
PhilMr Avatar asked Sep 11 '14 16:09

PhilMr


3 Answers

You basically wrote the regex yourself:

xx|af|an|bf|bn|cf|cn

like image 75
Brian Stephens Avatar answered Sep 30 '22 17:09

Brian Stephens


You wrote the regular expression yourself as stated previously, you could simplify it to...

var re = /xx|[abc][fn]/
like image 25
hwnd Avatar answered Sep 30 '22 16:09

hwnd


Try this:

^(xx|af|an|bf|bn|cf|cn)$

xx  => Correct
af  => Correct
aff => Incorrect
kk  => Incorrect

Live demo

like image 44
CMPS Avatar answered Sep 30 '22 17:09

CMPS