JS:从字符串中提取特定文本

时间:2018-06-18 07:17:51

标签: javascript

我有一个像这样的字符串......

var str = "6 validation errors detected: Value '' at 'confirmationCode' failed to satisfy constraint: Member must satisfy regular expression pattern: [\S]+; Value '' at 'confirmationCode' failed to satisfy constraint: Member must have length greater than or equal to 1; Value at 'password' failed to satisfy constraint: Member must satisfy regular expression pattern: [\S]+; Value at 'password' failed to satisfy constraint: Member must have length greater than or equal to 6; Value at 'username' failed to satisfy constraint: Member must satisfy regular expression pattern: [\p{L}\p{M}\p{S}\p{N}\p{P}]+; Value at 'username' failed to satisfy constraint: Member must have length greater than or equal to 1";

我想提取所有" unique"以单词开头的行......"价值" ......

所以期望的产出是......

  • 价值'' at' confirmationCode'未能满足约束
  • 密码值'未能满足约束
  • 用户名'的值失败 满足约束

这是我到目前为止所尝试的......

var x = str.split("\;|\:")  // This is NOT working
console.log(x);

var z = y.filter(word => word.indexOf("Value") > -1) // Also this needs to be tweaked to filter unique values
console.log(z);

性能是个问题,所以我更喜欢最优化的解决方案。

1 个答案:

答案 0 :(得分:3)

您可以使用单个正则表达式,不需要splitfilter或循环或其他所需的测试:

var str = "6 validation errors detected: Value '' at 'confirmationCode' failed to satisfy constraint: Member must satisfy regular expression pattern: [\S]+; Value '' at 'confirmationCode' failed to satisfy constraint: Member must have length greater than or equal to 1; Value at 'password' failed to satisfy constraint: Member must satisfy regular expression pattern: [\S]+; Value at 'password' failed to satisfy constraint: Member must have length greater than or equal to 6; Value at 'username' failed to satisfy constraint: Member must satisfy regular expression pattern: [\p{L}\p{M}\p{S}\p{N}\p{P}]+; Value at 'username' failed to satisfy constraint: Member must have length greater than or equal to 1";

console.log(
  str.match(/((^|Value)[^:]+)(?!.*\1)/g)
);