0

I am having trouble with regex here.

Say i have this input:

608094.21.1.2014.TELE.&BIG00Z.1.1.GBP

My regex looks like this

(\d\d\d\d\.\d?\d\.\d?\d)|(\d?\d\.\d?\d\.\d?\d?\d\d)

I want to extract the date 21.1.2014 out of the string, but all i get is

8094.21.1

I think my problem here is, that 21.1.2014 starts within the (wrong) match before. Is there a simple way to make the matcher look for the next match not after the end of the match before but one character after the beginning of the match before?

3
  • Perhaps regex alone is not the best tool for this job. Commented Jul 7, 2017 at 10:44
  • What you want is to do something like "\d*(\d{4}.\d{1,2}.\d{1,2})|(\d{1,2}\.\d{1,2}.\d{2,4})" Commented Jul 7, 2017 at 10:47
  • Can you add few more examples to make it clear. Commented Jul 7, 2017 at 11:20

3 Answers 3

1

You could use a regex like this:

\d{1,2}\.\d{1,2}\.\d{4}

Working demo

Or shorten it and use:

(\d{1,2}\.){2}\d{4}
Sign up to request clarification or add additional context in comments.

Comments

1

If the date is always surrounded by dot:

\.(\d\d\d\d\.\d?\d\.\d?\d|\d?\d\.\d?\d\.\d?\d?\d\d)\.

Comments

0

I hope this will help you.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        String x = "608094.21.1.2014.TELE.&BIG00Z.1.1.GBP";
        String pattern = "[0-9]{2}.[0-9]{1}.[0-9]{4}";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(x);
        if (m.find( )) {
            System.out.println("Found value: " + m.group() );
        }else {
            System.out.println("NO MATCH");
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.