RegEx in Java

September 27, 2010

Here's a snippet of Java code for validating an entire string aginst a regex:

boolean lValid = pValue.matches("[A-Za-z0-9_\\.\\-]+@[A-Za-z0-9\\.\\-]+\\.[A-Za-z\\.]+");

In this case we're validating that the string contains an email address. Note that this function implicitly adds a ^ at the start of the regex and a $ at the end - the string much match the regex without anything left over, for it to return true.

Groups

Here's how to process a regex and extract information using groups. This expects a message of format DRUM 500 20. We need to extract the 500 and 20.

Pattern lPattern = Pattern.compile("^[Dd][Rr][Uu][Mm]\\s*(\\d+)\s+(\\d+)\s*$");
Matcher lMatcher = lPattern.matcher(this.params.getTextContents());
lMatcher.find();

String lFirstNumber = lMatcher.group(1);
String lSecondNumber = lMatcher.group(2);

References

Tags: java regex