javascript - JS: Extracting specific text from a string
问题描述
I have a string like this ...
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";
I want to extract all the "unique" lines that start with the word ... "Value" ...
So expected output is ...
- Value '' at 'confirmationCode' failed to satisfy constraint
- Value at 'password' failed to satisfy constraint
- Value at 'username' failed to satisfy constraint
Here is what I have tried so far ...
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);
Performance is an issue, so I prefer the most optimized solution.
解决方案
您可以使用单个正则表达式,不需要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)
);
推荐阅读
- python - LangDetectException 文本中没有特征
- node.js - 在 puppeteer 中预加载一个 JS 文件
- ansible - 我正在尝试使用 ansible playbook 安装 helm,但在创建 RBAC 配置时出现错误
- firebase - 从 Firebase Firestore 中的嵌套地图对象中删除数组项
- r - 在使用 Knitr 的 R 中,如何获得在循环中创建的绘图图表以进行打印?
- linux - Unix命令打印第一句
- time - 运行 ansible-playbook 时如何测量和显示任务所花费的时间?
- css - React-MaterialUI:在App Bar - > Tabs - > Tab中将单个选项卡水平对齐到右侧和其他到左侧
- android - 状态栏下的应用栏标题颤动
- html - 如何水平滚动行项目