当前位置: 首页 > 知识库问答 >
问题:

单词中每个第一个字符和任何大写字母的正则表达式

薛元忠
2023-03-14

REGEX试图构建一个能够检索单词的第一个字母、该单词的任何其他大写字母以及每个第一个字母(包括同一单词中的任何大写字母)的正则表达式时遇到了麻烦

"WelcomeBack to NorthAmerica a great place to be" = WBTNAAGPTB
"WelcomeBackAgain to NorthAmerica it's nice here" = WBATNAINH
"Welcome to the NFL, RedSkins-Dolphins play today" = WTTNFLRSDPT

尝试使用此JUS获得前2个匹配项:

/([A-Z])|\b([a-zA-Z])/g

欢迎任何帮助,谢谢

共有3个答案

陆寒
2023-03-14

可以将regex用作:/\b[a-z]|[A-Z] /g;

<html>
   <head>
      <title>JavaScript String match() Method</title>
   </head>
   <body>
      <script type="text/javascript">
         var str = "WelcomeBack to NorthAmerica a great place to be";
         var re = /\b[a-z]|[A-Z]+/g;
         var found = str.match( re );
         found.forEach(function(item, index) {
            found[index] = item.toUpperCase();
        });
          document.write(found.join('')); 
      </script>
      
   </body>
</html>
刘德义
2023-03-14

试试这个:

let s = "WelcomeBack to NorthAmerica a great place to be";
s = s.match(/([A-Z])|(^|\s)(\w)/g);    // -> ["W","B"," t", " N"...]
s = s.join('');                        // -> 'WB t N...'
s = s.replace(/\s/g, '');              // -> 'WBtN...'
return s.toUpperCase();                // -> 'WBT ...'

/(?:([A-Z])|\b(\w))/g匹配每个大写字母([A-Z])OR|字符串开头后面的每个字母(\w)>或空白\s

(由于某种原因,我无法不捕获空格,因此执行了替换步骤。当然还有更好的技巧,但这是我发现的最具可读性的。)

尉迟墨竹
2023-03-14

您需要一个正则表达式,该正则表达式将匹配所有大写字母和出现在字符串开头或空格后的小写字母:

var re = /[A-Z]+|(?:^|\s)([a-z])/g; 
var strs = ["WelcomeBack to NorthAmerica a great place to be", "WelcomeBackAgain to NorthAmerica it's nice here", "Welcome to the NFL, RedSkins-Dolphins play today"];
for (var s of strs) {
  var res = "";
  while((m = re.exec(s)) !== null) {
    if (m[1]) {
       res += m[1].toUpperCase();
    } else {
      res += m[0];
    }
  }
  console.log(res);
}
 类似资料: