Ramazan Cinardere
Ramazan Cinardere

Reputation: 133

Extract data from String using regular Expression

i' going to extract business value from a String. But my problem is, that the string repeates each time in a loop. And the content syntax is always the same, but the content is changing. Thus I need a reg-expr which helps me to extract the data.

What I have tried so far: ("^\\d{1,2}(.{1})\\s([A-Za-z]{2})\\s(([A-Z]\\d{2,3}))\\s.")

But the the above provided pattern outputs me only the first three arguments: 01. Di F929

Sample String shows like following:

01. Di F929 * Fr F929 Fr FREI Mo S688 Mi S49 * Sa S57 Mo F929 
Do F224 So S49 Di X337 Fr F56 So FREI \n

Let me explain how the string is build.

  1. (01.) is a digit from 01 to 31.
  2. Following be shortWeekDays (German) (Mo, Di, Mi, ..)
  3. Word start with Character ends with digit (F929, S49, ...)
  4. (Optional) a special character like '*, X, ...'

Important:

Di + F929 + *
represents single data-block. Each String contains about 12 data-blocks.

My need is, a regular expression which match the above problem. Thanks in regard!

Upvotes: 0

Views: 77

Answers (1)

Mohsen
Mohsen

Reputation: 4633

This will help you:

(\d{1,2}\.)?\s*([A-Za-z]{2}\s+[A-Z0-9]+\s*[*X]?)\s*

Online Demo

Java code:

public class Test {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("(\\d{1,2}\\.)?\\s*([A-Za-z]{2}\\s+[A-Z0-9]+\\s*[*X]?)\\s*");
        String string = "01. Di F929 * Fr F929 Fr FREI Mo S688 Mi S49 * Sa S57 Mo F929 " +
            "Do F224 So S49 Di X337 Fr F56 So FREI \\n";

        Matcher m = pattern.matcher(string);

        while (m.find())
            System.out.println(m.group(2));
    }
}

Upvotes: 1

Related Questions