Skip to content

Instantly share code, notes, and snippets.

@piyush-malaviya
Created August 23, 2019 07:20
Show Gist options
  • Save piyush-malaviya/f5b35848ef783d573527027f93bca6ac to your computer and use it in GitHub Desktop.
Save piyush-malaviya/f5b35848ef783d573527027f93bca6ac to your computer and use it in GitHub Desktop.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexUtils {
//private static final String DISTANCE_PATTERN = "(?i)[0-9]{1,2}\\s??(?:mi|mile|miles|km)\\b";
private static final String DISTANCE_PATTERN = "(?i)((?:\\d+)?\\.?\\d+)\\s??(?:mi|mile|miles|km)\\b";
private static final String DISTANCE_UNIT_PATTERN = "(?i)(?:mi|mile|miles|km)\\b";
private static final String TIME_PATTERN = "(?i)[0-9]{1,2}\\s??(?:min|hr)";
private static final String TIME_UNIT_PATTERN = "(?i)(?:min|hr)";
private static final String FLOAT_NUMBER_PATTERN = "(?:\\d+)\\.\\d+\\b";
private static RegexUtils instance;
public static RegexUtils getInstance() {
if (instance == null) {
instance = new RegexUtils();
}
return instance;
}
public float getFirstNumberFromString(String data) {
Pattern pattern = Pattern.compile("(-?(?:\\d+)?\\.?\\d+)");
Matcher matcher = pattern.matcher(data);
if (matcher.find()) {
return Float.parseFloat(matcher.group());
}
return 0;
}
public String getFirstMatchingTimeData(String data) {
Pattern pattern = Pattern.compile(TIME_PATTERN);
Matcher matcher = pattern.matcher(data);
if (matcher.find()) {
return matcher.group().replaceAll(TIME_UNIT_PATTERN, "");
}
return "0";
}
public String getFirstMatchingDistanceData(String data) {
Pattern pattern = Pattern.compile(DISTANCE_PATTERN);
Matcher matcher = pattern.matcher(data);
if (matcher.find()) {
return matcher.group().replaceAll(DISTANCE_UNIT_PATTERN, "");
}
return "0";
}
public float getFirstMatchingRatingExceptTimeAndDistance(String data) {
data = data.replaceAll(DISTANCE_PATTERN, "");
data = data.replaceAll(TIME_PATTERN, "");
Pattern pattern = Pattern.compile(FLOAT_NUMBER_PATTERN);
Matcher matcher = pattern.matcher(data);
while (matcher.find()) {
Float val = Float.parseFloat(matcher.group());
if (val >= 0 && val <= 5) {
return val;
}
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment