英文:
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(/[!@#$%^&*()_+{}\[\]:;<>,.?~\\\-]/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 -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论