如何检查给定字符串中匹配的正则表达式数量?

huangapple go评论91阅读模式
英文:

How to check how many matched regex in given string

问题

我想知道在 JavaScript 中,给定字符串中正则表达式匹配了多少次。

例如:

var string = "AABBCCaabbcc123!@#"

我想知道:

  • 字符串中有多少个大写字母:6个,
  • 字符串中有多少个小写字母:6个,
  • 字符串中有多少个数字:3个,
  • 字符串中有多少个特殊字符:3个

是否有内置的 JavaScript 函数或简单的方法来实现这个逻辑?

非常感谢。

英文:

I want to get how many time a regex matched in given string in JavaScript.

For example:

var string = "AABBCCaabbcc123!@#"

I want to get:

  • How many upper case in string: 6,
  • How many lower case in string: 6,
  • How many numbers in string: 3,
  • How many special characters in stirng: 3

Is there built-in js functions or simple way to implement this logic?

Thank you very much.

答案1

得分: -1

你可以尝试以下方法:

function countCharacters(inputStr) {
    // 大写字母
    var uCount = (inputStr.match(/[A-Z]/g) || []).length;
    
    // 小写字母
    var lCount = (inputStr.match(/[a-z]/g) || []).length;
    
    // 数字
    var nCount = (inputStr.match(/\d/g) || []).length;
    
    // 特殊字符
    var sCount = (inputStr.match(/[!@#$%^&*()_+{}[\]:;<>,.?~\\\-]/g) || []).length;
    
    // 返回包含计数的对象
    return {
        uppercase: uCount,
        lowercase: lCount,
        numbers: nCount,
        specialCharacters: sCount
    };
}

var str = "AABBCCaabbcc123!@#";
var counts = countCharacters(str);

console.log("大写字母数量:", counts.uppercase); // 6
console.log("小写字母数量:", counts.lowercase); // 6
console.log("数字数量:", counts.numbers); // 3
console.log("特殊字符数量:", counts.specialCharacters); // 3

这段代码用于统计字符串中的大写字母、小写字母、数字和特殊字符的数量。你可以将需要统计的字符串赋值给str变量,然后调用countCharacters函数来获取统计结果。最后,使用console.log打印出各个统计值。

英文:

You can try the following way:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function countCharacters(inputStr) {
    //uppercase letters
    var uCount = (inputStr.match(/[A-Z]/g) || []).length;
    
    //lowercase letters
    var lCount = (inputStr.match(/[a-z]/g) || []).length;
    
    //numbers
    var nCount = (inputStr.match(/\d/g) || []).length;
    
    //special characters
    var sCount = (inputStr.match(/[!@#$%^&amp;*()_+{}\[\]:;&lt;&gt;,.?~\\\-]/g) || []).length;
    
    //return an object containing the counts
    return {
        uppercase: uCount,
        lowercase: lCount,
        numbers: nCount,
        specialCharacters: sCount
    };
}

var str = &quot;AABBCCaabbcc123!@#&quot;;
var counts = countCharacters(str);

console.log(&quot;Uppercase count:&quot;, counts.uppercase); //6
console.log(&quot;Lowercase count:&quot;, counts.lowercase); //6
console.log(&quot;Number count:&quot;, counts.numbers); //3
console.log(&quot;Special character count:&quot;, counts.specialCharacters); //3

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年8月9日 12:17:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定