0

I am trying to find multiple matches in my regex. Here is my regex

final Pattern p = Pattern.compile("^[0-9]{8}[#](FRI|SAT|SUN)[\r]$");
final Matcher m = p.matcher("09042012#SUN\r" + "09022012#FRI\r" + "09032012#SAT\r");
    while (m.find())
    {
        final String result = m.group();
        System.out.println(result);
    }

this works if the string has just one match, but if its consecutive matches it doesn't work. I have tried adding .+ at the end of my regex to make sure it atleast have one match. That doesn't work either.

What am I doing wrong??

3 Answers 3

2

You need to set the multiline flag:

final Pattern p = Pattern.compile("^[0-9]{8}[#](FRI|SAT|SUN)$", Pattern.MULTILINE);

This will allow the $ and ^ to match on the carriage returns \r in your input.

Sign up to request clarification or add additional context in comments.

Comments

0

^ and $ by default represent start/end of entire input (passed to Matcher), not start/end of lines.

If you want your regex to match only lines use in your regex Pattern.MULTILINE flag.
Also remove [\r] since characters after it are considered as placed in next line which means that $ placed after [\r] can only match end of next line - in other words you would find only match which have next line empty.

So your code should look more like

final Pattern p = Pattern.compile("^[0-9]{8}[#](FRI|SAT|SUN)$", Pattern.MULTILINE);
//                                                              ^^^^^^^^^^^^^^^^^
final Matcher m = p.matcher(
          "09042012#SUN\r" 
        + "09022012#FRI\r" 
        + "09032012#SAT\r");
while (m.find())
{
    final String result = m.group();
    System.out.println(result);
}

Comments

0

Remove line start ^ and line end $, your code would work:

final Pattern p = Pattern.compile("[0-9]{8}[#](FRI|SAT|SUN)[\r]");
final Matcher m = p.matcher("09042012#SUN\r" + "09022012#FRI\r" + "09032012#SAT\r");
    while (m.find())
    {
        final String result = m.group();
        System.out.println(result);
    }

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.