代码之家  ›  专栏  ›  技术社区  ›  Saurav Sahu

使用regex查找字符串中的第一个单词和最后几个单词

  •  0
  • Saurav Sahu  · 技术社区  · 7 年前

    使用这两个正则表达式 regPrefix regSuffix ,

    final String POEM = "1. Twas brillig, and the slithy toves\n" + 
                        "2. Did gyre and gimble in the wabe.\n" +
                        "3. All mimsy were the borogoves,\n" + 
                        "4. And the mome raths outgrabe.\n\n";
    
    String regPrefix = "(?m)^(\\S+)";   // for the first word in each line.
    String regSuffix = "(?m)\\S+\\s+\\S+\\s+\\S+$";  // for the last 3 words in each line.
    Matcher m1 = Pattern.compile(regPrefix).matcher(POEM);
    Matcher m2 = Pattern.compile(regSuffix).matcher(POEM);
    
    while (m1.find() && m2.find()) {
        System.out.println(m1.group() + " " + m2.group());
    }
    

    1. the slithy toves
    2. in the wabe.
    3. were the borogoves,
    4. mome raths outgrabe.
    

    有没有可能 合并这两个正则表达式

    String singleRegex = "(?m)^(\\S+)\\S+\\s+\\S+\\s+\\S+$";
    

    1 回复  |  直到 7 年前
        1
  •  6
  •   Tim Biegeleisen    7 年前

    String regex = "(?m)^(\\S+).*?((?:\\s+\\S+){3})$";
    Matcher m = Pattern.compile(regex).matcher(POEM);
    while (m.find()) {
        System.out.println(m.group(1) + m.group(2));
    }
    
    1. the slithy toves
    2. in the wabe.
    3. were the borogoves,
    4. mome raths outgrabe.
    

    Demo