Kevin Rhema Akhwilla
Kevin Rhema Akhwilla

Reputation: 105

Regex Between word

I have strings

Yangebup, Perth, Australia, Dated 2011-01-09

Jakarta, Indonesia, Dated 2013-08-24

So I want to get the location name Yangebup, Perth, Australia and Jakarta, Indonesia

How can I get that location name with regex? I have tried to use this code .+?,\bDated\b but the result is Match not found.

I also tried with regexpal.com to test my regex, with this code .+\bdated\b I can get it, but i have to use the Case insensitive (i) and the result still nothing when I write it on my java program.

Upvotes: 1

Views: 45

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521419

Use this regex pattern:

^(.*), Dated \d{4}-\d{2}-\d{2}$

List<String> locations = new ArrayList<String>();
locations.add("Yangebup, Perth, Australia, Dated 2011-01-09");
locations.add("Jakarta, Indonesia, Dated 2011-01-09");

String pattern = "^(.*), Dated \\d{4}-\\d{2}-\\d{2}$";
Pattern r = Pattern.compile(pattern);

for (String location : locations) {
    Matcher m = r.matcher(location);
    if (m.find()) {
        System.out.println("Found a location: " + m.group(1) );
    } else {
        System.out.println("NO MATCH");
    }
}

Output:

Found a location: Yangebup, Perth, Australia
Found a location: Jakarta, Indonesia

Upvotes: 1

Related Questions