首页 > 解决方案 > 包含比 a 更多 b 的字符串的 Javascript 正则表达式

问题描述

我正在尝试在 Javascript 中构造一个正则表达式,使字符串包含的 b 比 a 多。可以在任何地方包含其他字符,但 b 必须多于 a。有人可以帮忙吗?

标签: javascriptregex

解决方案


最简单的路线:

let moreAsThanBs = (str) => str.match(/a/ig).length > str.match(/b/ig).length;

console.log(moreAsThanBs("Are there more As than Bs in this sentence?"));
console.log(moreAsThanBs("Are there more As than BBBBBs in this sentence?"));


推荐阅读