Reputation: 193
I have a list of strings that I need to parse for the name and version, for example some strings look like this:
App Name 1.2.5
AppName 7.8.b
The App Name 7.0
I want to have two list of Strings one with the app name and one with the version number so one list is:
App Name
AppName
The App Name
Then the other list will be
1.2.5
7.8.b
3.0
I have tried just using a space to split the strings, but it would be easiest if the name was always in index 0 and the version is always in index 1. So I tried "\\d" (split by digits), however that didn't work like I thought it was. Any help would be appreciated, and thanks in advance
Upvotes: 2
Views: 317
Reputation: 29680
Try with " (?=\\d)"
that is a space followed by an digit which is not consumed (via zero-width positive lookahead)
Upvotes: 0
Reputation: 120516
Split isn't really appropriate here. Try using a matcher instead and use the group
method to get the app name and version.
Pattern p = Pattern.compile("^(\\D*[^\\d\\s])\\s*(\\d.*)", Pattern.DOT_ALL);
Matcher m = p.matcher(myString);
if (m.find()) {
String appName = m.group(1);
String versionNumber = m.group(2);
...
}
To understand how the regular expression works, take a look at the below:
^
means start matching at the start
(
starts group 1 which will hold the version name
\\D*
which starts with any number of non-digits
[^\\d\\s]
and ends with something that is neither a digit nor a space.
)
end of group 1
\\s*
which might be separated from the version number by zero or more spaces.
(
Group 2 contains the version number.
\\d
It starts with a digit
.*
and continues the rest of the input.
)
The end.
Upvotes: 5