1

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.

3
  • 1
    You don't need regex in this case. You can use a combination of substring and indexof. You could also treat the URL as a Path (definitely hackish and not the recommended usage) if you know the index of the element relative to the name count in advance. Commented Apr 17, 2019 at 11:15
  • 1
    Is your input always URL? Commented Apr 17, 2019 at 11:15
  • 1
    Also can your URL look like http://server.com/application/index.php?ord=asc&date=today#info? What is expected result if word would also be application? Commented Apr 17, 2019 at 11:20

2 Answers 2

2

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 
Sign up to request clarification or add additional context in comments.

1 Comment

It's better than mine version +1
0

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.

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.