简体   繁体   English

如何将2个字母的特定组合与正则表达式匹配

[英]how to match specific combination of 2 letters with regex

given this set of letters 给定这组字母

xx | xx | af | af | an | 一个| bf | bf | bn | bn | cf | cf | cn 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. 我可以轻松地用开关盒对解决方案进行硬编码,但我认为regex是更优雅的解决方案。

您基本上是自己编写正则表达式的:

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

如前所述,您自己编写了正则表达式,可以将其简化为...

var re = /xx|[abc][fn]/

Try this: 尝试这个:

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

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

Live demo 现场演示

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 工作演示

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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