Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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