Home » Java » Fix issue with regex expression getting first word in string in Java?-Exceptionshub

Fix issue with regex expression getting first word in string in Java?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am running a simple Java application and I want to grab the very first word in each string that I pass. So I did a str.split(" "); but I realized that my string that I have is very dynamic and it is constantly changing. So I pick up a , tagged on to the string which once I pass as a parameter crashes my code. So I am trying to find a particualry regex expression to just grab the very first words up until either a space, coma, period, or etc.

Example String:

WebServer, Config where AppConfig.display ends-with '/conf/workers.properties'  and Config.content.content contains 'worker.lyc_' and Config.parent.guid==WebServer.guid and exists(WebServer.container.virtualHosts.serverName contains 'www.laffatservices.gix.com')

My goal would to be to just grab WebServer.

How to&Answers:

If your goal is to grab only the first word then here is your regex ^[A-Za-z]{2,}.

Note that this matches a sequence of, at least two, capital and lower letters. And that match must be only in the start.

Hope that helps your case.

Answer:

If you want to find() first word which is NOT comma, whitespace, etc. you can use negated character class [^ ] and place inside all characters which you don’t want. This will result in creating character class which will accept all other characters.

In your case you can use code like:

String yourText = "WebServer, Config where AppConfig.display ends-with '/conf/workers.properties'  and Config.content.content contains 'worker.lyc_' and Config.parent.guid==WebServer.guid and exists(WebServer.container.virtualHosts.serverName contains 'www.laffatservices.gix.com')";
Pattern p = Pattern.compile("[^,\s]+");
Matcher m = p.matcher(yourText);
if (m.find()){
    String firstMatch = m.group();
    System.out.println(firstMatch);
}else{
    //handle case where there is no match found.
}

Output: WebServer

NOTE: Using find() will also allow you to find word even when your text starts with characters you want to skip like when String yourText = ",,,foo,,"; result would be foo.