简体   繁体   中英

Regular Expression in Java: How to refer to “matched patterns”?

I was reading the Java Regular Expression tutorial, and it seems only to teach to test whether a pattern matched or not, but does not tell me how to refer to a matched pattern.

For example, I have a string "My name is xxxxx". And I want to print xxxx. How would I do that with Java regular expressions?

Thanks.

What tutorial were you reading ? The sun's one tackles that topic quite thoroughly, but you have to read it correctly :)

Capturing a part of a string is done through the parentheses. If you want to capture a group in a string, you have to put this part of the regular expression in parentheses. The groups are defined in the order the parentheses appear, and the group with index 0 represents the whole string.

For instance, the regexp " Day ([0-9]+) - Note ([0-9]+) " would define 3 groups :

  • group(0) : The whole string
  • group(1) : The first group in the regexp, that is to say the day number
  • group(2) : The second group in the regexp, that is to say the note number

As for the actual code and how to retrieve the groups you've defined in your regexp, have a look at the Java documentation, especially the Matcher class and its group method : http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html

You can test your regexps with that very useful tool : http://www.cis.upenn.edu/~matuszek/General/RegexTester/regex-tester.html

Hope this helped, Cheers

Note the use of parentheses in the pattern and the group() method on Matcher

import java.util.regex.*;

public class Example {
    static public void main(String[] args) {
        Pattern regex = Pattern.compile("My name is (.*)");
        String s = "My name is Michael";
        Matcher matcher = regex.matcher(s);

        if (matcher.matches()) {
            System.out.println("original string: " + matcher.group(0));
            System.out.println("first group: " + matcher.group(1));
        }
    }
}

Output is:

original string: My name is Michael
first group: Michael

You can use the Matcher group(int) method:

 Pattern p = Pattern.compile("My name is (.*)");
  Matcher m = p.matcher("My name is akf");
  m.find();
  String s = m.group(1); //grab the first group*
  System.out.println(s);

output:

akf

* look at matching groups

Matcher m = Pattern.compile("name is (.*)").matcher("My name is Ross");
if (m.find()) {
  System.out.println(m.group(0));
  System.out.println(m.group(1));
}

The parens form a capturing group . Group 0 is the entire pattern and group 1 is the back reference .

The above program outputs:

name is Ross
Ross

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