我有一个像这样的字符串...
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";
我想提取所有以单词...“Value”...开头的“独特”行...
所以预期的输出是......
- “confirmationCode”处的值“”未能满足约束
- “password”的值未能满足约束
- “用户名”的值未能 满足约束
这是我到目前为止所尝试过的......
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);
性能是一个问题,所以我更喜欢最优化的解决方案。
最佳答案
您可以使用单个正则表达式,不需要 split
或 filter
或循环或其他测试:
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)
);
关于javascript - JS : Extracting specific text from a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50904353/