Using Regular Expressions to Capture Substrings in a Group

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Using Regular Expressions to Capture Substrings in a Group

This is a Java example of how to use regular expressions to capture substrings in a group.

[edit] Source Code of RegexGroupExample

  • Package: com.exampleshow.string.regex
  • File: RegexGroupExample.java
package com.exampleshow.string.regex;
 
/**
 * @author Code Panda
 * Copyright (C) 2008 Java ExampleShow (http://java.exampleshow.com)
 *
 * This code is free software; you can redistribute it and/or modify it.
 * However, this header must remain intact and unchanged. Additional
 * information may be appended after this header. Publications based on
 * this code must also include an appropriate reference.
 * 
 * This code is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE.
 *
 */
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexGroupExample {
 
    public void testGroup() {
	String candidate = "Java2008ExampleShow";
	String[] regexs = new String[] { 
		"([a-zA-Z]*)(\\d*)(\\w*)",
		"(\\D*)(\\d*)(\\w*)",
		"(\\w*)(\\d*)(\\D*)",
		"(\\d*)(\\w*)(\\D*)" 
		};
 
	for (int i = 0; i < regexs.length; i++) {
 
	    matcherFindGroup(candidate, regexs[i]);
 
	}
    }
 
    private void matcherFindGroup(String src, String regex) {
	System.out.println("\nTry with [" + regex + "]...");
	Pattern pattern = Pattern.compile(regex);
 
	Matcher matcher = pattern.matcher(src);
 
	if (matcher.find()) {
	    System.out.println("GROUP 0:" + matcher.group(0));
	    System.out.println("GROUP 1:" + matcher.group(1));
	    System.out.println("GROUP 2:" + matcher.group(2));
	    System.out.println("GROUP 3:" + matcher.group(3));
	} else {
	    System.out.println("No matches.");
	}
 
	System.out.println("Done!");
    }
 
    public static void main(String[] args) {
	RegexGroupExample rge = new RegexGroupExample();
	rge.testGroup();
    }
 
}

[edit] What Result You Can Get

Run the program, you will get:



Try with [([a-zA-Z]*)(\d*)(\w*)]...
GROUP 0:Java2008ExampleShow
GROUP 1:Java
GROUP 2:2008
GROUP 3:ExampleShow
Done!

Try with [(\D*)(\d*)(\w*)]...
GROUP 0:Java2008ExampleShow
GROUP 1:Java
GROUP 2:2008
GROUP 3:ExampleShow
Done!

Try with [(\w*)(\d*)(\D*)]...
GROUP 0:Java2008ExampleShow
GROUP 1:Java2008ExampleShow
GROUP 2:
GROUP 3:
Done!

Try with [(\d*)(\w*)(\D*)]...
GROUP 0:Java2008ExampleShow
GROUP 1:
GROUP 2:Java2008ExampleShow
GROUP 3:
Done!


[edit] Required External Library for this Java Example

Need nothing.

http://www.ase2009.com/ online casino 132 http://www.hellzyea.com/health health insurance 8DDD http://www.yourautoinsurancesite.com/ auto insurance quotes 135811 http://www.makemeasammich.com/ auto insurance mcnxu
Personal tools