DEV Community

loizenai
loizenai

Posted on

Java Regular Expression to extract data from a Text

https://grokonez.com/java/java-sample-practices/java-regular-expression-to-extract-data-from-string

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.

    
    public class Weather {
    private String location;
    private int temperature;
    
    // constructor, getter/setter methods...
    }
    
  • 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:

    
    String pattern = "(Location:)(\\s*.+)(,)(.*Temperature:\\s+)(\\d+)";
    

    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:

More at:

https://grokonez.com/java/java-sample-practices/java-regular-expression-to-extract-data-from-string

Java Regular Expression to extract data from a Text

Top comments (0)