javascript - 用于匹配第一个单词的正则表达式
问题描述
我有以下输出“高优先级”的道具 {priority},有没有办法可以将它简单地呈现为“高”?我可以使用标准 js 或类似下面的东西吗?
var getPriority = {priority};
var priority = getPriority.replace( regex );
console.log( priority );
我该如何解决这个问题?
解决方案
如果您希望使用正则表达式执行此操作,则此表达式会执行此操作,即使“优先级”一词可能有拼写错误:
(.+)(\s[priorty]+)
它可以简单地使用捕获组在“优先级”之前捕获您想要的单词。如果您希望为其添加任何边界,这样做会容易得多,特别是如果您的输入字符串会更改。
图形
此图显示了表达式的工作原理,您可以在此链接中可视化其他表达式:
const regex = /(.+)(\s[priorty]+)/gmi;
const str = `high priority
low priority
medium priority
under-processing pririty
under-processing priority
400-urget priority
400-urget Priority
400-urget PRIority`;
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}`);
});
}
性能测试
这个 JavaScript 片段使用简单的 100 万次for
循环显示了该表达式的性能。
repeat = 1000000;
start = Date.now();
for (var i = repeat; i >= 0; i--) {
var string = "high priority";
var regex = /(.+)(\s[priorty]+)/gmi;
var match = string.replace(regex, "$1");
}
end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. ");
推荐阅读
- javascript - 我正在尝试实现文件下载,但所有下载的文件都已损坏(图像)或空(pdf)
- spring-boot - 是否可以在 Spring Boot 项目中配置 Amazon Keyspaces?
- asp.net-mvc - 调整主页面foreach中的ajax部分视图项
- html - 在 HTML 画布中呈现的图像可实现的最大更新率?
- powershell - Remove-Item (和 [System.IO.File]::Delete() )删除正在使用的文件
- swift - 为什么 SwiftUI 中的 getter 即使多行也不需要使用 return 关键字?
- typescript - Typescript & webpack-dev-server 显示错误
- javascript - 我如何在这个应用程序中使用 jest?
- arduino - 从 DeepSleep 模式返回后 Mpu6050 未连接到 Esp32
- r - 是否有一种功能(或一种优化方法)可以比循环更快地读取许多文本文件?