Java Regular Expression to extract data from a Text

This tutorial shows you how to extract data from a Text using Regular expression.

Related article: Java Regular Expression Overview – Syntax

I. Problem

Assume that we already have a string that contains Weather data like this:

What we need is to store them in Java Objects using Regular Expression.

II. Practice

– First, we need a data model class to store Weather data for each item we get.

– Next, we have to make our own pattern to extract data (location, temperature) from input text.
There are many ways to do this, for more details for how to choose syntax for the string pattern, please read this article: Java Regular Expression Overview – Syntax.
In this case, we can create a pattern like this:

You can see that we have 5 groups, the data we need are only in the 2nd group and 5th group.
So the Java code should be similar to:

III. Source code

Weather.java

MainApp.java

Run the code, the result shows in console window:


Related Posts



Got Something To Say:

Your email address will not be published. Required fields are marked *

*