如何处理Regex作为字符串返回?

时间:2017-10-08 15:57:08

标签: javascript json ajax regex string

请注意,我尝试了其他SO帖子关于regexp的一些建议,没有人帮忙! 来到这个问题 -

我有这样的JSON数据(原文:meteor:react-packages source code):

{
  VISA: {
    cardPattern: "/^4/",
    cardNumberLength: 16,
    cvv: "required",
    cvvLength: 3,
    displayText: "Visa"
  },
  MASTERCARD: {
    cardPattern: "/^5[1-5]/",
    cardNumberLength: 16,
    cvv: "required",
    cvvLength: 3,
    displayText: "Master"
  },
  MAESTRO: {
    cardPattern:
      "/^(50|63|66|5[6-8]|6[8-9]|600[0-9]|6010|601[2-9]|60[2-9]|61|620|621|6220|6221[0-1])/",
    cardNumberLength: 19,
    cvv: "optional",
    cvvLength: 4,
    displayText: "Maestro"
  }
}

请查看字符串格式的cardPattern属性。我如何利用它来测试一个字符串(比如说445)。 例如,“/ ^ 4 /”。test(mysttring)不起作用。并且     var reg = new RegExp(“/ ^ 4 /”)返回一个奇怪的// ^ 4 //永远不会匹配mystring。 如何处理正则表达式的这种响应?只是为了更明确,如何处理响应['VISA']。cardPattern.test(4545)应该有效,但没有!

而且,响应不是JSON格式,而是对象内部的对象。解析此类响应的最佳方法是什么?我尝试了for-in循环,但返回'VISA','MASTERCARD'和'MAESTRO'(字符串),这不是我想要的。

2 个答案:

答案 0 :(得分:2)

您必须先使用new RegExp()构造函数来解析正则表达式。

但是,您必须删除前导和尾部斜杠:

function parseCardPattern(cardPattern) {
  return new RegExp(cardPattern.substr(1, cardPattern.length - 2));
}

您现在可以使用regexp对象进行测试:

const visaPattern = parseCardPattern(response['VISA'].cardPattern);
console.log(visaPattern.test('4242424242'));  // => True

答案 1 :(得分:0)

如果我没有误解你的问题。像这样json.VISA.cardPattern抓住cardPattern然后尝试这样

let json = {"VISA":{"cardPattern":"/^4/","cardNumberLength":16,"cvv":"required","cvvLength":3,"displayText":"Visa"},"MASTERCARD":{"cardPattern":"/^5[1-5]/","cardNumberLength":16,"cvv":"required","cvvLength":3,"displayText":"Master"},"MAESTRO":{"cardPattern":"/^(50|63|66|5[6-8]|6[8-9]|600[0-9]|6010|601[2-9]|60[2-9]|61|620|621|6220|6221[0-1])/","cardNumberLength":19,"cvv":"optional","cvvLength":4,"displayText":"Maestro"}};
const regex = json.VISA.cardPattern;
const str = `4545`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}