Home » Java » java – Regular expression: the string must contains sequence of words-Exceptionshub

java – Regular expression: the string must contains sequence of words-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have such code:

        String regexp = "[\w\W]*(London)[\w\W]*(Paris)[\w\W]*";

        String test1 = "London Paris";
        boolean t1 =  Pattern.matches(regexp, test1);
        System.out.println(t1);

        String test2 = "London to Paris";
        boolean t2 =  Pattern.matches(regexp, test2);
        System.out.println(t2);

        String test3 = "from London to Paris";
        boolean t3 =  Pattern.matches(regexp, test3);
        System.out.println(t3);

        String test4 = "from (London) -> (Paris)";
        boolean t4 =  Pattern.matches(regexp, test4);
        System.out.println(t4);

I need all boolean to be true. Now, this condition is met, but the regex seems to me not too effective. How can I change this?

How to&Answers:

You can go with something faster than a regex:

public static boolean isValid(String str) {
        int indexOfLondon = str.indexOf("London");
        int indexOfParis = str.indexOf("Paris");

        return indexOfLondon != -1 && indexOfParis != -1 && indexOfLondon < indexOfParis 
    }

Regex is avoidable here.

Answer:

You may want to use word boundaries as well. Like this regex:

.*\b(London)\b.*(Paris)\b.*

The reason is that you current regex will also match LondonaParis or aLondona Parisaaa. Not sure if you want that.

If you keep a word boundary around the specific names you are looking for, these strings won’t pass.

However, I second @Ali Ben Zarrouk’s point of not needing regexes for this.