O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Finding Matching Text Using a Regular Expression

String pattern = "[TJ]im";
											Pattern regPat = Pattern.compile(pattern);
											String text = "This is jim and Timothy.";
											Matcher matcher = regPat.matcher(text);
											if (matcher.find()) {
											String matchedText = matcher.group();
											}

In this pattern, we make use of the Pattern and the Matcher classes. We use the static compile() method of the Pattern class to compile a pattern string into a Pattern object. Once we have the regPat Pattern object, we use the matcher() method, passing in the text string we want to match against. The matcher() method returns an instance of the Matcher class. Finally, we call the group() method of the Matcher class to obtain the matched text. The matched text in this phrase will be the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required