如何检查给定字符串中匹配的正则表达式有多少个

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 {
        大写字母: uCount,
        小写字母: lCount,
        数字: nCount,
        特殊字符: sCount
    };
}

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

console.log("大写字母计数:", counts.大写字母); // 6
console.log("小写字母计数:", counts.小写字母); // 6
console.log("数字计数:", counts.数字); // 3
console.log("特殊字符计数:", counts.特殊字符); // 3

请注意,我已经将代码中的注释翻译成中文,以便更容易理解代码的功能。如果您需要任何进一步的帮助,请告诉我。

英文:

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-2.html
匿名

发表评论

匿名网友

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

确定