1

I have a problem with not working REGEX. I dont know what I am doing wrong. My code:

String test = "timetable:xxxxxtimetable:;   timetable: fullihhghtO;";
Pattern p = Pattern.compile("\\btimetable:(.*);");
//also tried "timetable:(.*);" and "(\\btimetable:)(.*)(;)"
Matcher m = p.matcher(test);

while(m.find()) {
    System.out.println("S:" + m.start() + ", E:" + m.end());
    System.out.println("x: "+ test.substring(m.start(), m.end()));
}

Expected result:

(1) "timetable:xxxxxtimetable:"
(2) "timetable: fullihhghtO"

I thanks for any help.

0

2 Answers 2

1

A non-capturing group could be handy in our case:

    String test = "timetable:xxxxxtimetable:;   timetable: fullihhghtO;";
    Pattern p = Pattern.compile("(?:\\btimetable:(.*?);)+"); // <-- here
    Matcher m = p.matcher(test);

    int i = 1;
    while (m.find()) {
        System.out.println(i + ") "+ m.group(1));
        i++;
    }

OUTPUT

1) xxxxxtimetable:
2)  fullihhghtO

Regex explained:
(?:\\btimetable:(.*?);)+ by using the non-capturing (?:\\btimetable:...) we'll consume the "timetable:" without capturing it, then the second matching group (.*?) captures what we want to capture (everything between \btimetable: and ;). Pay special attention to the non-greedy term: .*? which means that we'll consume the minimum possible amount of characters until the ;. If we won't use this lazy form, the regex will use "greedy" default mode and will consume all the characters until the last ; in the string!

Now, all that is relevant if you wanted to catch only the unique part, but if you wanted to catch the whole thing:

1) timetable:xxxxxtimetable:;
2) timetable: fullihhghtO;

It can be done easily by modifying the line with the regex to:

Pattern p = Pattern.compile("\\b(timetable:.*?;)+");

which is even simpler: only one capturing group (see that we still have to use the non-greedy mode!).

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

1 Comment

I cannot add you point, because I am low level, but I really thanks you for your time and for your help, first case is what I needed, but I wanted to do it somehow through test.split(":"), but you show me better solution thanks. You helped me a lot.
0

You don't need to use regex, a simple split would do it :

public static void main(String[] args) throws IOException {
    String test = "timetable:xxxxxtimetable:;   timetable: fullihhghtO;";
    String[] array = test.split(";");
    String str1 = array[0].trim();
    String str2 = array[1].trim();

    System.out.println(str1 + "\n" + str2);      //timetable:xxxxxtimetable:
                                                 //timetable: fullihhghtO
}

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.