fork download
  1. import java.util.Objects;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4.  
  5. class Ideone {
  6. public static void main(String[] args) {
  7. final Pattern pattern = Pattern.compile(
  8. "\\b(?<!\\.)(?<number>\\d{1,4})(?:(\\.\\d{1,2})?)(?<unit> ml)\\b",
  9. Pattern.CASE_INSENSITIVE);
  10.  
  11. final Matcher matcher = pattern.matcher("5432 ml");
  12. final Matcher matcher2 = pattern.matcher("54321 ml");
  13. final Matcher matcher3 = pattern.matcher("1234.0 ml");
  14. final Matcher matcher4 = pattern.matcher("Start 12345.0 ml end");
  15.  
  16. final String result = matcher.find()
  17. ? matcher.group("number") + matcher.group("unit")
  18. : "";
  19. final String result2 = matcher2.find()
  20. ? matcher2.group("number") + matcher2.group("unit")
  21. : "";
  22. final String result3 = matcher3.find()
  23. ? matcher3.group("number") + matcher3.group("unit")
  24. : "";
  25. final String result4 = matcher4.find()
  26. ? matcher4.group("number") + matcher4.group("unit")
  27. : "";
  28.  
  29. System.out.println(Objects.equals(result, "5432 ml"));
  30. System.out.println(Objects.equals(result2, ""));
  31. System.out.println(Objects.equals(result3, "1234 ml"));
  32. System.out.println(Objects.equals(result4, ""));
  33. }
  34. }
Success #stdin #stdout 0.1s 54664KB
stdin
Standard input is empty
stdout
true
true
true
true