简体   繁体   中英

getting matching regular expressions in java

String.split(String regex) splits the string around a given regular expression and returns an String array. But I am interested in the regex matches and would like them to be returned as string array instead of strings around them. For example, In case of trival regex like ":" it probably wouldn't matter. But there are regexes which would match a particular date in a paragraph and I would like to get all these dates which may be different each time. I checked the jdk api but couldn't find any such methods. Is there any method that I can make use of?. Any help would much appreciated.

Take a look at java.util.regex package Matcher and Pattern classes:

http://download.oracle.com/javase/6/docs/api/java/util/regex/package-summary.html

Just use the Java regular expression API

Pattern pat = Pattern.compile("\\d");
Matcher mat= pat.matcher("Foo99Bar66Baz");
while(mat.find()) { 
      System.out.println(mat.group());
}

You can find simple but quite comprehensive examples for startup in the following link

http://www.vogella.de/articles/JavaRegularExpressions/article.html

Also Pattern and Matcher usage example in:

http://www.vogella.de/articles/JavaRegularExpressions/article.html#regexjava

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM