简体   繁体   中英

java parse a certain subsection using string split

Help would be appreciated, I have a string such as: APP_RUNTIME_ERB3242322_1_P3A97.tar.gz

and I would like to parse it and get the following: P3A97

The string will change in time but basically I need the last five alphanumerical letters before the .tar.gz part whenever I get feed this string data.

I can use the java string split method but I do not know what regex I can use to get the last 5 characters.

您可以使用lastIndexOf

str.substring(str.lastIndexOf("_") + 1, str.lastIndexOf(".tar.gz"))

You can split based on "_" initially and then take the last token that it gives you. Then you can split on "." and take the first token that it gives you. This of course depends on whether the format will always have the same number of tokens per split.

Demonstrated:

APP_RUNTIME_ERB3242322_1_P3A97.tar.gz into APP

RUNTIME

ERB3242322

1

P3A97.tar.gz

And then split P3A97.tar.gz into P3A97 tar and gz

...
String str = "APP_RUNTIME_ERB3242322_1_P3A97.tar.gz";
String lastChars = str.substring(str.length() - 12).replace(".tar.gz", "");

System.out.print(lastChars);

P3A97

I need the last five alphanumerical letters before the .tar.gz part whenever I get feed this string data.

I can use the java string split method but I do not know what regex I can use to get the last 5 characters

You do NOT need regexp here. Besides what you have mentioned, if .tar.gz can be assumed to be at the end of the string then you are looking for a substring :

starting at (length of the string) - length(.tar.gz) - 5
ending at above index + 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM