sags
sags

Reputation: 13

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!

Upvotes: 0

Views: 243

Answers (3)

Bohemian
Bohemian

Reputation: 425033

Why split? Just:

String appName = input.replaceAll(".*?\\.(.*)\\.\\d+\\..*", "$1");

This also correctly handles a dot then digits within the application name, but only works correctly if you know the input is in the expected format.

To handle "bad" input by returning blank if the pattern is not matched, be more strict and use an optional that will always match (replace) the entire input:

String appName = input.replaceAll("^application\\.(.*)\\.\\d+\\.\\w+$|.*", "$1");

Upvotes: 0

logi-kal
logi-kal

Reputation: 7880

With split(), you could save key.split("\\.") in a String[] s and, in a second time, join from s[1] to s[s.length-3].

With regexes you can do:

String appName = key.replaceAll("application\\.(.*)\\.\\d+\\.\\w+")", "$1");

Upvotes: 0

Andreas
Andreas

Reputation: 159096

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.

Upvotes: 1

Related Questions