首页 > 解决方案 > 用于匹配第一个单词的正则表达式

问题描述

我有以下输出“高优先级”的道具 {priority},有没有办法可以将它简单地呈现为“高”?我可以使用标准 js 或类似下面的东西吗?

var getPriority = {priority};
var priority = getPriority.replace( regex );
console.log( priority );

我该如何解决这个问题?

标签: javascriptregexstringregex-groupregex-greedy

解决方案


如果您希望使用正则表达式执行此操作,则此表达式会执行此操作,即使“优先级”一词可能有拼写错误:

(.+)(\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.  ");


推荐阅读