sags sags - 1 year ago 58
Java Question

Java - Regular Expressions Split on character after and before certain words

I'm having trouble figuring out how to grab a certain part of a string using regular expressions in JAVA. Here's my input string:

application.APPLICATION NAME.123456789.status

I need to grab the portion of the string called
. I can't simply split on the period character becuase
may itself include a period. The first word,
", will always remain the same and the characters after
will always be numbers.

I've been able to split on period and grab the 1st index but as I mentioned,
may itself include periods so this is no good. I've also been able to grab the first and second to last index of a period but that seems ineffecient and would like to future-proof by using REGEX.

I've googled around for hours and haven't been able to find much guidance. Thanks!

Answer Source

You can use ^application\.(.*)\.\d with find(), or application\.(.*)\.\d.* with matches().

Sample code using find():

private static void test(String input) {
    String regex = "^application\\.(.*)\\.\\d";
    Matcher m = Pattern.compile(regex).matcher(input);
    if (m.find())
        System.out.println(input + ": Found \"" + + "\"");
        System.out.println(input + ": **NOT FOUND**");
public static void main(String[] args) {
    test("application.APPLICATION NAME.123456789.status");
    test("application.App 55 name.123456789.status");
    test("bad input");


application.APPLICATION NAME.123456789.status: Found "APPLICATION NAME"
application.Other.App.Name.123456789.status: Found "Other.App.Name"
application.App 55 name.123456789.status: Found "App 55 name" Found ""
bad input: **NOT FOUND**

The above will work as long as "status" doesn't start with a digit.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download