【问题标题】:Count number of comma-separated substrings inside single quotes in Java计算Java中单引号内逗号分隔的子字符串的数量
【发布时间】:2012-03-28 18:21:06
【问题描述】:

我有一个格式如下的字符串。 'abc','def','ghi' 等

我想使用正则表达式查找此字符串中的单词数(单引号内的单词)。

编辑: 试过这个,我认为这行得通:

        int c = 0;
        Pattern pattern = Pattern.compile("'[^*]'");
        Matcher matcher = pattern.matcher(myString);
        while(matcher.find()){
           c++;
        }

【问题讨论】:

  • 正则表达式不是用于此目的的最佳武器
  • 尝试学习正则表达式:)

标签: java regex


【解决方案1】:

为什么要使用正则表达式来计数? 您可以使用 str.split(",") 并获取数组大小?

【讨论】:

  • 然后您可以使用类似'[^']*' 的匹配项,它查找',然后是不是' 的X 个字符,最后是另一个'
  • 我不认为 split 是正确的选择。它比需要的更强大。他只是想统计,的出现次数...
  • @Murat 你说得对,不需要创建数组的开销。
  • @coder247 我会给你上正则表达式的第一堂免费课:除非你必须使用正则表达式,否则不要使用正则表达式。
【解决方案2】:

使用正则表达式

String regex = "your regular expression here";   // Regex that matches double words
Pattern p = Pattern.compile(regex);     // Compile Regex
Matcher m = p.matcher("your upcoming string");         // Create Matcher
int count = 0;
while (m.find()) {
  count++;
}
system.out.println("Number of match = "+count);

使用字符串

String str = "'abc','def','ghi'";

String wordsWithQuotes[] = str.split(",");
System.out.println("no of words = "+wordsWithQuotes.length);

System.out.println("no of words = "+str.split(",").length);

【讨论】:

    【解决方案3】:

    这不是正则表达式,但它工作得很快

    int numberOfWords = (str.length() - str.replaceAll("'","").length()) / 2;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多