ab11
ab11

Reputation: 20090

Cleaner way to parse this String?

I expect a String of format `%s_%d.y'. For example, "aabsa_124.y" or "x_5.y".

I am extracting the numeric portion of the String with the below code, any suggestions for a cleaner way to extract the number?

String suffix = input.split("_")[1];
String numeric = suffix.split("\\.")[0];
int number = Integer.parseInt(numeric)

Upvotes: 0

Views: 79

Answers (4)

Piyush
Piyush

Reputation: 1162

You can also use RegExp to better capture the number you are looking for. The regExp here uses both a positive lookahead(?=) and a lookbehind(?<=). Simple groups can also be used if you dont want the lookahead/lookbehind logic.

String input = "aabsa_124.y";
Pattern p = Pattern.compile("(?<=\\_)\\d+(?=\\.\\w+)");
Matcher m = p.matcher(input);
if (m.find()) {
    int number = Integer.parseInt(m.group());
    System.out.println(number);//124
}

This would also match strings like "str_str_2.y".

Upvotes: 1

vbuhlev
vbuhlev

Reputation: 509

The important thing is to abstract the parsing logic in its own method with good name and unit tests. That will make your code clean.

Personally I would use regular expression for this.

Your implementation is ok for the inputs you described, but it won't work for examples like "str_str_2.y" or "str_2.34.y".

Before using some tricky one liner remember this:

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

Martin Fowler, 2008.

Upvotes: 0

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59986

You can replace all non degit with empty then you can parse your int :

int number = Integer.parseInt(input.replaceAll( "[^\\d]", ""));

If your String contain many ints, and you want to extract this ints you can use Patterns for example :

String input = "aabsa_124_155.y";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(input);

while (m.find()) {
    System.out.println(m.group());
}

Output

124
155

Upvotes: 0

giliev
giliev

Reputation: 3058

Something like this maybe:

        String s = "aabsa_124.y";
        int number = Integer.parseInt(s.replaceAll("[^\\d]", ""));

Upvotes: 0

Related Questions