Java Regular Expression to extract data from a Text
Java
207
regular
1
expression
2
Male avatar

loveprogramming viết ngày 04/05/2021

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

Bình luận


White
{{ comment.user.name }}
Bỏ hay Hay
{{comment.like_count}}
Male avatar
{{ comment_error }}
Hủy
   

Hiển thị thử

Chỉnh sửa

Male avatar

loveprogramming

451 bài viết.
79 người follow
Kipalog
{{userFollowed ? 'Following' : 'Follow'}}
Cùng một tác giả
Male avatar
1 0
Tutorial Link: (Link) (Ảnh) Django is a Pythonbased free and opensource web framework that follows the modeltemplateview architectural pattern. A...
loveprogramming viết 6 tháng trước
1 0
Male avatar
1 0
https://loizenai.com/angular11nodejspostgresqlcrudexample/ Angular 11 Node.js PostgreSQL Crud Example (Ảnh) Tutorial: “Angular 11 Node.js Postg...
loveprogramming viết 5 tháng trước
1 0
Male avatar
1 0
Angular Spring Boot jwt Authentication Example Github https://loizenai.com/angularspringbootjwt/ (Ảnh) Tutorial: ” Angular Spring Boot jwt Authe...
loveprogramming viết 5 tháng trước
1 0
{{like_count}}

kipalog

{{ comment_count }}

bình luận

{{liked ? "Đã kipalog" : "Kipalog"}}


Male avatar
{{userFollowed ? 'Following' : 'Follow'}}
451 bài viết.
79 người follow

 Đầu mục bài viết

Vẫn còn nữa! x

Kipalog vẫn còn rất nhiều bài viết hay và chủ đề thú vị chờ bạn khám phá!