import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(# the number at the beginning\n"
+ "[-+]? # optional leading sign\n"
+ "\\d+# the digits to the left of the decimal\n"
+ "(?:\\.\\d+)? # an optional decimal amount\n"
+ ")\n\n"
+ "(#the start of the units\n"
+ " [a-zA-Z]+ # must be alphabetic\n"
+ " (?: # followed optionally by zero-or-more\n"
+ " \\/[a-zA-Z]+ # slash-followed-by-text as in /hr\n"
+ " |\n"
+ " \\^[-+]?\\d+(?:\\.\\d+)? # a caret followed by our same/initial digit pattern\n"
+ " )*\n"
+ ")";
final String string = "Very much a stupid beginner question, but trying to make a regex expression which would take in \"5ms-1\", \"17km/h\" or \"9ms^-2\" etc. with these ambiguous units and ambiguous formats. Please help, I can't manage it\n\n"
+ "-5mph\n"
+ "6.8m/h\n"
+ "+8liters/hectacre^2\n\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.COMMENTS);
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