Abhishek
Abhishek

Reputation: 680

How to extract a word in java after a given word in using regex in java

I am trying to extract a word after a given word. eg: if my string is "http://localhost:8080/api/rest/loan/application/1007/applicant/951/pan", then i want to extract the word which ever comes after application (assume application comes only once in the string).

In this case I want to extract 1007. For now I have tried this using Java

(.*?^)(.*?)application/[0-9]*.

This is giving me output as http://localhost:8080/api/rest/loan/application/1007. But I want only 1007 as my output.

Upvotes: 1

Views: 174

Answers (2)

guroosh
guroosh

Reputation: 652

How about

    String a = "http://localhost:8080/api/rest/loan/application/1007/applicant/951/pan";
    a = a.replaceAll("(.*?^)(.*?)application/", "");
    String[] b = a.split("/");
    System.out.println(b[0]);

string replace function takes exact string as input while replaceAll takes a regex as an input argument.

Upvotes: 0

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You can use positive look behind to ensure the matched text is preceded by application/ using this regex,

(?<=application/)[^/]+

Here, [^/]+ part will capture any text except /, giving you your desired text 1007

Regex Demo

Java code,

String s = "http://localhost:8080/api/rest/loan/application/1007/applicant/951/pan";
Pattern p = Pattern.compile("(?<=application/)[^/]+");
Matcher m = p.matcher(s);
if (m.find()) {
    System.out.println(m.group());
}

Prints,

1007

Another easier and more performant way to do the same task would be to use following grouping pattern,

/application/([^/]+)

and capture the contents of group1.

Regex Demo with grouping pattern

Notice, this is much faster as well as will work broadly as look arounds are sometimes not supported in some dialects.

Java code,

String s = "http://localhost:8080/api/rest/loan/application/1007/applicant/951/pan";
Pattern p = Pattern.compile("/application/([^/]+)");
Matcher m = p.matcher(s);
if (m.find()) {
    System.out.println(m.group(1));
}

Prints,

1007 

Upvotes: 2

Related Questions