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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25793070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:01:57  来源:igfitidea点击:

how to match specific combination of 2 letters with regex

javascriptregex

提问by PhilMr

given this set of letters

鉴于这组字母

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

xx | 阿夫| 一个 | 男朋友 | 十亿 | 比照 | 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.

我可以使用 switch case 轻松地对解决方案进行硬编码,但我认为 regex 是一个更优雅的解决方案。

回答by Brian Stephens

You basically wrote the regex yourself:

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

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

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

回答by hwnd

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

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

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

回答by CMPS

Try this:

试试这个:

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

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

Live demo

现场演示

回答by Federico Piazza

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

在此处输入图片说明