【问题标题】:RegEx for matching the first word用于匹配第一个单词的正则表达式
【发布时间】:2019-05-08 17:03:45
【问题描述】:

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

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

我该如何解决这个问题?

【问题讨论】:

  • 只做getPriority.replace('priority', '').trim() 会满足您的需求吗?
  • 你可以在空格上分割并拉出第一个。 var [ priority ] = getPriority.split(' '),这里不需要正则表达式。

标签: javascript regex string regex-group regex-greedy


【解决方案1】:

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

(.+)(\s[priorty]+)

它可以简单地使用捕获组在“优先级”之前捕获您想要的单词。如果您希望为其添加任何边界,这样做会容易得多,特别是如果您的输入字符串会更改。

图表

此图显示了表达式的工作原理,您可以在此 link 中可视化其他表达式:

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 sn-p 使用简单的 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. ? ");

【讨论】:

    【解决方案2】:

    您可以使用substring 来获取您需要的字符串

    var str = 'high priority';
    console.log(str.substring(0, 4));
    // expected output: "high"
    

    所以在你的代码中

    var getPriority = {priority};
    var priority = getPriority.priority.substring(0, 4);
    console.log( priority );
    

    【讨论】:

      【解决方案3】:

      您可以使用.split() 简单地获取字符串的唯一第一个元素: 下面的代码将显示字符串的第一个单词:

      var getPriority = {priority};
      console.log( getPriority.priority.split(' ', 1)[0]);
      

      或者如果优先级值最后总是有priority这个词,你可以去掉它,把它作为.split()的分隔符:

      var getPriority = {priority};
      console.log( getPriority.priority.split(' priority')[0] );
      

      【讨论】:

        猜你喜欢
        • 2010-10-07
        • 1970-01-01
        • 2011-08-13
        • 2013-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-17
        • 1970-01-01
        相关资源
        最近更新 更多