最新消息:20210917 已从crifan.com换到crifan.org

【已解决】Java的正则表达式Regex中,如何查找所有的匹配的项

Java regex crifan 6077浏览 0评论

【问题】

java中的正则表达式类是regex,想要去调用,可以查找到,所有的匹配的项。

【解决过程】

1.参考官网:

http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

没有找到相关的。

2.通过NetBeans中,查看find相关的函数,也没有类似于findall之类的函数。

3.网上找了找,找到这个:

Find all matches

Java regex example code to find all matches in a string

然后写出类似的代码:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package match_digit_and_num;

//http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author CLi
 */
public class Match_digit_and_num {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        /*
         * 如何匹配出类似11A11、22A22、33A33、44B44、55B55这样的字符串,正则表达式怎么写?java中用,跪求各大侠
         * http://zhidao.baidu.com/question/507118070.html
         */
        String digitNumStr = "11A11、22A22、33A33、44B44、55B55";
        //String digitNumStr = "11A11";
        Pattern digitNumP = Pattern.compile("(?<twoDigit>\\d{2})[A-Z]\\k<twoDigit>");
        Matcher foundDigitNum = digitNumP.matcher(digitNumStr);
        
        // Find all matches
        while (foundDigitNum.find()) {
          // Get the matching string
          String digitNumList = foundDigitNum.group();
          System.out.println(digitNumList);
        }
    }
}

然后是可以匹配到对应的内容的:

11A11

22A22

33A33

44B44

55B55

 

【总结】

Java中的正则方面的功能,的确还是很弱的。连一次性的获得所有匹配的项,都这么麻烦。

比如C#,Python中麻烦多了。

又一次的验证了那句,Java的正则做的很挫。

转载请注明:在路上 » 【已解决】Java的正则表达式Regex中,如何查找所有的匹配的项

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
92 queries in 0.183 seconds, using 23.35MB memory