英文:
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(/[!@#$%^&*()_+{}\[\]:;<>,.?~\\\-]/g) || []).length;
//return an object containing the counts
return {
uppercase: uCount,
lowercase: lCount,
numbers: nCount,
specialCharacters: sCount
};
}
var str = "AABBCCaabbcc123!@#";
var counts = countCharacters(str);
console.log("Uppercase count:", counts.uppercase); //6
console.log("Lowercase count:", counts.lowercase); //6
console.log("Number count:", counts.numbers); //3
console.log("Special character count:", counts.specialCharacters); //3
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论