Narendra Rawat
Narendra Rawat

Reputation: 363

Match first occurrence from back in regex

I have to match strings between "JJ." and the second occurrence of "," from back.

e.g:

In Mackintosh v. Watkins (1904) 1 C L J 31, Brett and Mookerjee, JJ.

desired output: Brett and Mookerjee

Currently what i am using matches the first "," to the JJ.

my pattern:

",.*.[^,]*JJ\b"

Upvotes: 0

Views: 1721

Answers (2)

nu11p01n73R
nu11p01n73R

Reputation: 26667

You can either use look arounds or capturing groups.

  • Look ahead solution

    (?<=, )[^,]*(?=,[^,]*JJ\b)
    
    • (?<=, ) Look behind, checks if the string is preceded by a ,
    • (?=,[^,]*JJ\b) Look ahead. Checks if the string is followed by , and then anything other than , and JJ

    Regex Demo

  • Capturing goups

    ,([^,]*),[^,]*JJ\b
    

    Regex Demo

    Here the capturing group 1 will contain the string Brett and Mookerjee

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174726

Use capturing groups.

Matcher m = Pattern.compile(",\\s*([^,]+),[^,]*\\bJJ\\b").matcher(s);
if(m.find())
{
System.out.println(m.group(1));
}

DEMO

Upvotes: 0

Related Questions