public class MixedNumberRegex {
public static void main(String[] args) {
Pattern FRACTION_PATTERN = Pattern.compile("(?:(\\d+)\\s+)?(\\d+)/(\\d+)");
Matcher m = FRACTION_PATTERN.matcher("1/2 + 1 1/2");
System.out.print(m.group(1));
}
}
Hi, I am trying to extract out the mixed number from the string. Is my pattern expression correct? From the example, I want the output to be "1 1/2".
I keep getting the exception
Exception in thread "main" java.lang.IllegalStateException: No match found at java.util.regex.Matcher.group(Unknown Source) at MixedNumberRegex.main(MixedNumberRegex.java:15) `
You can simplify your regex a bit and do it this way:
Pattern FRACTION_PATTERN = Pattern.compile("(?:\\d+\\s+)?\\d/\\d");
Matcher m = FRACTION_PATTERN.matcher("1/2 + 1 1/2");
while (m.find()) {
String found = m.group();
}
It will find 1/2
and 1 1/2
.
If you want to capture only 1 1/2
, use pattern:
Pattern FRACTION_PATTERN = Pattern.compile("\\d+\\s+\\d/\\d");