sags sags - 4 months ago 11
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
"APPLICATION NAME"
. I can't simply split on the period character becuase
APPLICATION NAME
may itself include a period. The first word,
"application
", will always remain the same and the characters after
"APPLICATION NAME"
will always be numbers.

I've been able to split on period and grab the 1st index but as I mentioned,
APPLICATION NAME
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

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 \"" + m.group(1) + "\"");
    else
        System.out.println(input + ": **NOT FOUND**");
}
public static void main(String[] args) {
    test("application.APPLICATION NAME.123456789.status");
    test("application.Other.App.Name.123456789.status");
    test("application.App 55 name.123456789.status");
    test("application.App.55.name.123456789.status");
    test("bad input");
}

Output

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"
application.App.55.name.123456789.status: Found "App.55.name"
bad input: **NOT FOUND**

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

Comments