newday
newday

Reputation: 3878

How to extract the first word after one particular word from regex

This is the code I tried

public static final String EXAMPLE_TEST = "ddd with fff Node  preceded"
            + " by Class Application  bzxcd by " 
            + "Class aaa ds  preceded by Class bbbb xxxx Ass";

          public static void main(String[] args) {
           boolean clarrification =  EXAMPLE_TEST.matches(".*\\bClass\\b.*");


           String pattern = "(.*?\\bClass\\b.*?)(\\s+)(\\w+)";

           System.out.println(EXAMPLE_TEST.replaceFirst(pattern, "$3$2")); 

What I am trying here is to only extract the first occurrence after 'Class' word. In my case it extracts the Application but it is followed by rest of the words.

How to fix this?

Upvotes: 1

Views: 1812

Answers (1)

anubhava
anubhava

Reputation: 784958

You can use this simplified regex:

String pattern = ".*?\\bClass\\s+(\\w+)\\b.*";

System.out.println(EXAMPLE_TEST.replaceFirst(pattern, "$1"));
//=> Application

This regex matches 0 or more characters before Class (non-greedy) using .*? followed by word boundary and text Class. It is followed by 1 or more spaces and then next word being captured in a group#1 using (\\w+). It must be followed by .* to match rest of the string. In the replacement we just use back-reference $1 to get matched word back in final output.

Upvotes: 1

Related Questions