Issue
Java 8 here. I am trying to parse a semver (or at least, my flavor of semver) string and extract out its main segments:
- Major version number
- Minor version number
- Patch number
- Qualifier (
RC
,SNAPSHOT
,RELEASE
, etc.)
Here is my code:
String version = "1.0.1-RC";
Pattern versionPattern = Pattern.compile("^[1-9]\\d*\\.\\d+\\.\\d+(?:-[a-zA-Z0-9]+)?$");
Matcher matcher = versionPattern.matcher(version);
if (matcher.matches()) {
System.out.println("\n\n\matching version is: " + matcher.group(0));
System.out.println("\nmajor #: " + matcher.group(1));
System.out.println("\nminor #: " + matcher.group(2));
System.out.println("\npatch #: " + matcher.group(3));
System.out.println("\nqualifier: " + matcher.group(4) + "\n\n\n");
}
When this runs, I get the following output on the console:
matching version is: 1.0.1-RC
2019-10-18 14:32:05,952 [main] 84b37cef-70f9-4ab8-bafb-005821699766 ERROR c.s.f.s.listeners.StartupListener - java.lang.IndexOutOfBoundsException: No group 1
What do I need to do to my regex and/our use of the Matcher API so that I can extract:
1
as the major number0
as the minor number1
as the patch numberRC
as the qualifier
Any ideas?
Solution
NOTE:
- You should not escape
m
in a string literal,\m
is not a valid string escape sequence and the code won't compile Matcher#matches()
requires a full string match, no need to add^
and$
anchors- To be able to reference
Matcher#group(n)
, you need to define the groups in the pattern in the first place. Wrap the parts you need with pairs of unescaped parentheses.
Use
String version = "1.0.1-RC";
Pattern versionPattern = Pattern.compile("([1-9]\\d*)\\.(\\d+)\\.(\\d+)(?:-([a-zA-Z0-9]+))?");
Matcher matcher = versionPattern.matcher(version);
if (matcher.matches()) {
System.out.println("matching version is: " + matcher.group(0));
System.out.println("major #: " + matcher.group(1));
System.out.println("minor #: " + matcher.group(2));
System.out.println("patch #: " + matcher.group(3));
System.out.println("qualifier: " + matcher.group(4) + "\n\n\n");
}
See the Java demo, output:
matching version is: 1.0.1-RC
major #: 1
minor #: 0
patch #: 1
qualifier: RC
Answered By - Wiktor Stribiżew
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.