【问题标题】:UVa #494 - regex [^a-zA-z]+ to split words using JavaUVa #494 - 正则表达式 [^a-zA-z]+ 使用 Java 拆分单词
【发布时间】:2012-12-29 06:25:35
【问题描述】:

我在玩UVa #494,我设法用下面的代码解决了它:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Main {    
    public static void main(String[] args) throws IOException{
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while((line = in.readLine()) != null){
            String words[] = line.split("[^a-zA-z]+");
            int cnt = words.length;
            // for some reason it is counting two words for 234234ddfdfd and words[0] is empty
            if(cnt != 0 && words[0].isEmpty()) cnt--; // ugly fix, if has words and the first is empty, reduce one word
            System.out.println(cnt);
        }
        System.exit(0);
    }
}

我构建了正则表达式"[^a-zA-z]+" 来拆分单词,例如字符串abc..abcabc432abc 应该拆分为["abc", "abc"]。但是,当我尝试使用字符串432abc 时,结果是["", "abc"] - words[] 的第一个元素只是一个空字符串,但我希望只有["abc"]。我不明白为什么这个正则表达式给了我第一个元素 "" 在这种情况下。

【问题讨论】:

    标签: java regex logic


    【解决方案1】:

    查看拆分参考页面:split reference

    分隔符的每个元素定义一个单独的分隔符。如果 两个分隔符相邻,或者在开头找到一个分隔符 或此实例的结尾,对应的数组元素包含 空的。下表提供了示例。

    因为你有几个连续的分隔符,你得到空数组元素

    【讨论】:

      【解决方案2】:

      打印字数

      public static void main(String[] args) throws IOException {
              BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
              String line;
              while ((line = in.readLine()) != null) {
                  Pattern pattern = Pattern.compile("[a-zA-z]+");
                  Matcher matcher = pattern.matcher(line);
                  int count = 0;
                  while (matcher.find()) {
                      count++;
                      System.out.println(matcher.group());
                  }
                  System.out.println(count);
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-11
        • 1970-01-01
        • 1970-01-01
        • 2011-06-22
        • 1970-01-01
        • 1970-01-01
        • 2013-08-19
        • 2015-01-07
        相关资源
        最近更新 更多