Search code examples
javaregexreplacefindcapturing-group

Saving substrings using Regular Expressions


I'm new to regular expressions in Java (or any language, for that matter) and I'm wanting to do a find using them. The tricky part that I don't understand how to do is replace something inside the string that matches.

For example, if the line I'm looking for is

Person item6 [can {item thing [wrap]}]

I'm able to write a regex that finds that line, but finding what the word "thing" is (as it may differ among different lines) is my problem. I may want to either replace that word with something else or save it in a variable for later. Is there any easy way to do this using Java's regex engine?


Solution

  • Yes. You wrap it in "capturing groups", which is just some ( ) around the part of the regular expression matching the interesting word.

    Here is an example:

    public static void main(String[] args) {
    
        Pattern pat = Pattern.compile("testing (\\d+) widgets");
    
        String text = "testing 5 widgets";
    
        Matcher matcher = pat.matcher(text);
    
        if (matcher.matches()) {
            System.out.println("Widgets tested : " + matcher.group(1));
        } else {
            System.out.println("No match");
        }
    
    }
    

    Pattern and Matcher come from java.util.regex. There are some shortcuts in the String class, but these are the most flexible