计算Javascript中正则表达式的匹配数 [英] Count number of matches of a regex in Javascript

查看:151
本文介绍了计算Javascript中正则表达式的匹配数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个正则表达式来计算一大块文本中的空格/制表符/换行符的数量。所以我天真地写了以下内容: -

I wanted to write a regex to count the number of spaces/tabs/newline in a chunk of text. So I naively wrote the following:-

numSpaces : function(text) { 
    return text.match(/\s/).length; 
}

由于某些未知原因,它总是返回 1 。上述陈述有什么问题?我已经解决了以下问题: -

For some unknown reasons it always returns 1. What is the problem with the above statement? I have since solved the problem with the following:-

numSpaces : function(text) { 
    return (text.split(/\s/).length -1); 
}


推荐答案

tl; dr :通用模式计数器

// THIS IS WHAT YOU NEED
const count = (str) => {
  const re = /YOUR_PATTERN_HERE/g
  return ((str || '').match(re) || []).length
}

对于那些到达这里的人来说,寻找一种通用的方法来计算字符串中正则表达式模式的出现次数,并且不想要如果出现零,则失败,此代码就是您所需要的。这是一个演示:

For those that arrived here looking for a generic way to count the number of occurrences of a regex pattern in a string, and don't want it to fail if there are zero occurrences, this code is what you need. Here's a demonstration:

/*
 *  Example
 */

const count = (str) => {
  const re = /[a-z]{3}/g
  return ((str || '').match(re) || []).length
}

const str1 = 'abc, def, ghi'
const str2 = 'ABC, DEF, GHI'

console.log(`'${str1}' has ${count(str1)} occurrences of pattern '/[a-z]{3}/g'`)
console.log(`'${str2}' has ${count(str2)} occurrences of pattern '/[a-z]{3}/g'`)

原始答案

初始代码的问题在于您错过了全局标识符

The problem with your initial code is that you are missing the global identifier:

>>> 'hi there how are you'.match(/\s/g).length;
4

没有 g 正则表达式的一部分它只匹配第一个匹配项并停在那里。

Without the g part of the regex it will only match the first occurrence and stop there.

另请注意,正则表达式将连续计算两次空格:

Also note that your regex will count successive spaces twice:

>>> 'hi  there'.match(/\s/g).length;
2

如果不可取,​​你可以这样做:

If that is not desirable, you could do this:

>>> 'hi  there'.match(/\s+/g).length;
1

这篇关于计算Javascript中正则表达式的匹配数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆