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"
+ "(#units\n"
+ " \\/? #optional slash\n"
+ " [a-zA-Z]+ # must be alphabetic\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"
+ "5ms-1\n"
+ "17km/h\n"
+ "9ms^-2\n\n"
+ "-5mph\n"
+ "6.8m/h\n"
+ "+8liters/hectacre^2\n\n"
+ "5/h\n"
+ "1m^2s^2\n\n"
+ "this will also match the 21st century, 7eleven, 3M, and similar things.\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