Java 字符串中大写字母的正则表达式

Java 字符串中大写字母的正则表达式,java,regex,Java,Regex,就我个人而言,我不明白为什么这个正则表达式不起作用。它应该在给定的字符串中找到大写字母并给出计数。欢迎提出任何意见 以下是单元测试代码: public class RegEx { @Test public void testCountTheNumberOfUpperCaseCharacters() { String testStr = "abcdefghijkTYYtyyQ"; String regEx = "^[A-Z]+$";

就我个人而言,我不明白为什么这个正则表达式不起作用。它应该在给定的字符串中找到大写字母并给出计数。欢迎提出任何意见

以下是单元测试代码:

public class RegEx {

    @Test
    public void testCountTheNumberOfUpperCaseCharacters() {
        String testStr = "abcdefghijkTYYtyyQ";
        String regEx = "^[A-Z]+$";

        Pattern pattern = Pattern.compile(regEx);

        Matcher matcher = pattern.matcher(testStr);

        System.out.printf("Found %d, of capital letters in %s%n", matcher.groupCount(), testStr);

    }
}
  • 您没有在匹配器上调用
    匹配
    查找
    。它没有做任何工作

  • getGroupCount
    是错误的调用方法。你的正则表达式没有捕获组,即使它有,也不会给你字符数


  • 您应该使用
    find
    ,但是使用不同的正则表达式,一个没有锚定的正则表达式。我还建议使用适当的Unicode字符类:
    “\\p{Lu}+”
    。在
    while(m.find())
    循环中使用此选项,并在每个步骤中累积从
    m.group(0).length()获得的字符总数。

    它不起作用,因为您有两个问题:

  • 正则表达式不正确,对于ASCII字母,它应该是
    “[A-Z]”
    ,对于Unicode大写字母,它应该是
    \p{Lu}
  • 您没有在
    matcher.groupCount()之前调用
    while(matcher.find())
  • 正确的代码:

    public void testCountTheNumberOfUpperCaseCharacters() {
        String testStr = "abcdefghijkTYYtyyQ";
        String regEx = "(\\p{Lu})";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(testStr);
        while (matcher.find())
            System.out.printf("Found %d, of capital letters in %s%n", 
              matcher.groupCount(), testStr);
    
    }
    
    更新:使用此简单得多的单行代码来计算字符串中的Unicode大写字母数:

    int countuc = testStr.split("(?=\\p{Lu})").length - 1;
    
    它应该在给定的字符串中找到大写字母并给出计数

    不,它不应该这样做:
    ^
    $
    锚阻止它这样做,迫使它查找完全由大写字符组成的非空字符串

    此外,在未定义组的表达式中,不能期望组计数不是零(无匹配项)或一(单个匹配项)

    如果坚持使用正则表达式,请使用不带锚的简单
    [a-Z]
    表达式,并在循环中调用
    matcher.find()
    。但是,更好的方法是调用字符串中的字符,并计算命中率:

    int count = 0;
    for (char c : str.toCharArray()) {
        if (Character.isUpperCase(c)) {
            count++;
        }
    }
    

    您所写的模式在行首和行尾之间查找1个或多个大写字母…如果行中有任何小写字符,它将不匹配。

    这应该满足您的要求

    @Test
    public void testCountTheNumberOfUpperCaseCharacters() {
      String testStr = "abcdefghijkTYYtyyQ";
      String regEx = "[A-Z]+";
      Pattern pattern = Pattern.compile(regEx);
      Matcher matcher = pattern.matcher(testStr);
      int count = 0;
      while (matcher.find()) {
        count+=matcher.group(0).length();
      }
      System.out.printf("Found %d, of capital letters in %s%n", count, testStr);
    }
    

    在本例中,我使用正则表达式(regex)使用Java计算给定字符串中的大小写字母数

    import java.util.regex.*;
    import java.util.Scanner;
    import java.io.*;
    public class CandidateCode {
        public static void main(String args[] ) throws Exception {
            Scanner sc= new Scanner(System.in);
        //  Reads the String of data entered in a line
            String str = sc.nextLine();
    
        //counts uppercase letteres in the given String 
            int countuc = str.split("([A-Z]+?)").length; 
    
        //counts lowercase letteres in the given String 
            int countlc = str.split("([a-z]+?)").length; 
    
            System.out.println("UpperCase count: "+countuc-1);
            System.out.println("LowerCase count: "+countlc-1);
       }
    }
    

    将正则表达式更改为 [A-Z]检查所有大写字母的出现

    请参考下面的示例,该示例使用模式计算字符串中的大写字母数

    @Test
    public void testCountTheNumberOfUpperCaseCharacters() {
        Pattern ptrn = Pattern.compile("[A-Z]");
        Matcher matcher = ptrn.matcher("ivekKVVV");
        int from = 0;
        int count = 0;
        while(matcher.find(from)) {
            count++;
            from = matcher.start() + 1;
        }
        System.out.println(count);
    }
    

    }您也可以使用Java正则表达式,例如:

    .+[\p{javaUpperCase}].+ 
    
    我的工作项目的一个例子:

    groupCount
    不计算字符数。答案永远都是一样的。我没有说它算数。无论如何,让我编辑它来回答这个问题。OP是计算字符数,因此使用“正确的代码”意味着您的解决方案计算字符数。我在上一次编辑中提供了一个简单的代码来计算大写字母。@anubhava:我试着提交一个编辑,但不允许出现微小的,单字符编辑:您应该删除描述中的
    +
    (2项列表中的#1),以匹配您的代码您可以(可能)通过使用
    [A-Z]+
    count+=matcher.group(0.length()
    )来加快它的速度。Regex解决方案和您的解决方案中哪一个性能更好@dasblinkenlight@MaheshVarma我并没有对它进行基准测试,但我的解决方案应该要快得多。这是非常重要的一次
    [A-Z]
    Č
    不匹配,在我看来(来自中欧)这是一件大事;)<另一方面,code>Character.isUpperCase(“Č”)
    正确地报告了
    true
    。@vektor如果您试图搜索任何语言中匹配的大写字母+regex,数千个问题和答案都会引起您的注意。@revo可能,但我在搜索“在字符串中仅保留大写字母”时发现了这个问题或者类似的东西,虽然它似乎在讨论一般情况,但它只适用于ASCII。因此,我试图强调这一点。不要只放一个代码,添加一些关于您的答案的描述,谢谢您的评论,我已经添加了一些关于代码的细节,希望这将有助于理解代码提到
    “\\p{Lu}+”
    是我在这里的关键部分。在看到你答案的这一部分之前,我已经开始悬赏了,我心里还有另一个答案,但至少我对你的答案投了赞成票。