6

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.

PhilMr
  • 475
  • 1
  • 5
  • 13
  • Try this solution: Here's [a link](http://stackoverflow.com/questions/13546187/how-to-match-any-combination-of-letters-using-regex)! – felixgondwe Sep 11 '14 at 16:58

4 Answers4

6

You basically wrote the regex yourself:

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

Brian Stephens
  • 5,161
  • 19
  • 25
6

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

var re = /xx|[abc][fn]/
hwnd
  • 69,796
  • 4
  • 95
  • 132
  • Or even `/xx|[abc][fn]/`. – Lynn Sep 11 '14 at 22:28
  • All of the answers are correct, but I'd choose this because it really matches the semantics of my use case: either xx or a possible combination between the characters abc with fn (they have specific meanings in my code). Thanks! – PhilMr Sep 12 '14 at 10:02
1

Try this:

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

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

Live demo

CMPS
  • 7,733
  • 4
  • 28
  • 53
  • Since the specification was "given two letters", the anchors seem unnecessary. –  Sep 11 '14 at 16:59
1

You can use this code:

// regex to match your words
var re = /\b(xx|af|an|bf|bn|cf|cn)\b/g; 

// your text string
var str = 'as ww zx af ad we re an ana ';
var m;

while ((m = re.exec(str)) != null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}

Working demo

enter image description here

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123