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

时间:2016-09-20 09:50:27

标签: javascript regex

我在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

尝试了这个juus获得前2场比赛:

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

欢迎任何帮助,谢谢

4 个答案:

答案 0 :(得分:3)

你需要一个匹配所有大写字母的正则表达式以及出现在字符串开头或空格后的小写字母:



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);
}




此处,[A-Z]+|(^|\s)([a-z])匹配多次出现:

  • [A-Z]+ - 一个或多个大写ASCII字母
  • | - 或
  • (?:^|\s) - 字符串开头(^)或空格(\s
  • ([a-z]) - 第1组:一个小写的ASCII字母。

答案 1 :(得分:1)

试试这个:

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])开头后面的每个字母|(\w)或空格^

(由于某些原因,我无法获取空白,因此\s步骤。当然有更好的技巧,但这是我发现的最可读的。)

答案 2 :(得分:1)

您可以将正则表达式用作:/\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>

答案 3 :(得分:1)

你可以尝试这个,它也会照顾空白

str = str.match(/([A-Z])|(^|\s)(\w)/g);
str = str.join('');
str=str.replace(/ /g,'');
return str.toUpperCase();