如何使用正则表达式匹配新生成的名称

时间:2014-01-09 15:53:08

标签: javascript regex prototype

我正在进行锻炼。我坚持第一次要求将正则表达式与新机器人名称相匹配的测试。

这是测试(我只处理那个没有x的人)。

var Robot = require('./ robot-name');

describe("Robot", function() {
  it("has a name", function() {
    var robot = new Robot();
    expect(robot.name).toMatch(/\w{2}\d{3}/);
  });

  xit("name is the same each time", function() {
    var robot = new Robot();
    expect(robot.name).toEqual(robot.name);
  });

  xit("different robots have different names", function() {
    var robotOne = new Robot();
    var robotTwo = new Robot();
    expect(robotOne.name).not.toEqual(robotTwo.name);
  });

  xit("is able to reset the name", function() {
    var robot = new Robot();
    var originalName = robot.name;
    robot.reset();
    var newName = robot.name;
    expect(originalName).not.toEqual(newName);
  });
});

我猜这是行不通的。

var Robot = function(){

  this.name = {};

  Robot.prototype.new = function(robotNumber){
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = 5;
    var newName = Math.random().toString(36).slice(-5);

    newName = MyRe.exec("/\w{2}\d{3}/");

    newName.push(robotNumber);
    this.name(newName);
  };


};
module.exports = Robot;

错误消息在第6行并响应: 预期{}匹配/ \ w {2} \ d {3} /。

如果有人能指出我在javascript中使用原型和正则表达式的大量资源方向,那将非常有帮助。谢谢。

2 个答案:

答案 0 :(得分:0)

MyRe应该是您的正则表达式,例如/\w{2}\d{3}/g.exec()应该接受您的字符串。您尚未定义MyRe。如果你想简洁一点,你可以写一些像/\w{2}\d{3}/.exec(newName)这样的东西。

在尝试阅读您的代码后,它完全没有意义。我甚至无法想象你的目标是什么。

答案 1 :(得分:0)

在你的正则表达式/\w{2}\d{3}/

\w{2}表示字符 (a-z, A-Z, 0-9, _) (2次)

\d{3}表示位数 (0-9) (3次)

\w{2}\d{3}可以表示为,

enter image description here

匹配的示例是:ab123