Javascript正则表达式不匹配正确

时间:2016-10-17 00:59:14

标签: javascript regex

这是我要针对“3x12”检查的格式。 “x”之前的第一个数字可以是2位数,但第一个数字不能是0.这个数字后面必须跟字母“x”,然后再加上与“x”之前相同的数字格式。

这是我的正则表达式:

        string[] movies = {
                "Star Wars Episode IV A New Hope",
                "Force of Hunger",
                "The Hunger Games Mockingjay",
                "Jaws 2",
                "The Shawshank Redemption",
                "Hunger Pain",
                "The Hunger Games",
                "Jaws: The Revenge",
                "The Hunger Games Catching Fire",
                "Rogue One A Star Wars Story",
                "Aqua Teen Hunger Force",
                "The Force Awakens Star Wars",
            };

        string[] kw = { "Star", "Wars", "Force", "Hunger", "Games", "The", "Jaws" };


        var group  = movies.GroupBy(p => kw.Count(k => p.Contains(k))).OrderByDescending(p=> p.Key);
        StringBuilder sb = new StringBuilder();

        foreach (var g in group)
        {
          sb.AppendLine("Group : " + g.Key);
            foreach (var s in g)
            {
                sb.AppendLine(s);
            }
        }

我在这里做错了什么?当我尝试“3x12”时为什么不匹配?

1 个答案:

答案 0 :(得分:2)

正如@nnnnnn所提到的 - 你的正则表达式应该调整

var r, i, l, tests = [ "3x12", "doggy", "5x1", "41x44", "66x", "x3", "0x2", "0x0", "656x0"];
r = /^[1-9]\d?x[1-9]\d?/;
l = tests.length;
for (i = 0; i < l; i++) {
        console.log(tests[i], r.test(tests[i]));
}

<强>输出

3x12 true
doggy false
5x1 true
41x44 true
66x false
x3 false
0x2 false
0x0 false
656x0 false