import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^P(?!$)((\\d+Y)|(\\d+\\.\\d+Y$))?((\\d+M)|(\\d+\\.\\d+M$))?((\\d+W)|(\\d+\\.\\d+W$))?((\\d+D)|(\\d+\\.\\d+D$))?(T(?=\\d)((\\d+H)|(\\d+\\.\\d+H$))?((\\d+M)|(\\d+\\.\\d+M$))?(\\d+(\\.\\d+)?S)?)??$";
final String string = "P1Y\n"
+ "P1.4Y\n"
+ "P1.4Y2M\n"
+ "P14Y2.5M\n"
+ "P14Y2.5MT1M\n"
+ "P2MT30M\n"
+ "P2MT30.5M\n"
+ "P2MT30.5M3S\n"
+ "PT6H\n"
+ "PT6.5H\n"
+ "PT6.5H12S\n"
+ "P5W\n"
+ "P5.2W\n"
+ "P5.2W1D\n"
+ "P3Y29DT4H35M59S\n"
+ "P1Y1M1DT2H12M34.23S\n\n\n"
+ "P\n"
+ "PT\n"
+ "P3MT";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html