Jump to content

[Snippet] Extract integers from a message


Recommended Posts

Posted (edited)

Example

1)

public static void main(String[] args) {
	String string = "1 snickers beats 5 mars";
	System.out.println(RegexUtil.extractAllIntegers(string));
	System.out.println(RegexUtil.extractFirstInteger(string));
}
[1, 5]
1 

2)

RS2Widget pointsTotal = getWidgets().singleFilter(getWidgets().getAll(), w -> w != null && w.isVisible() && w.getMessage() != null && w.getMessage().contains("Pest Points: "));
if(pointsTotal != null) {
     totalPoints = RegexUtil.extractFirstInteger(pointsTotal.getMessage());
}

Code:

public final class RegexUtil {

	public static final Pattern INTEGERS_PATTERN = Pattern.compile("-?\\d+");
	
	private RegexUtil() {
		
	}
	
	public static List<Integer> extractAllIntegers(String string) {
		List<Integer> result = new ArrayList<>();
		Matcher matcher = INTEGERS_PATTERN.matcher(string);
		while (matcher.find()) {
			result.add(Integer.parseInt(matcher.group()));
		}
		return result;
	}
	
	public static Integer extractFirstInteger(String string) {
		Matcher matcher = INTEGERS_PATTERN.matcher(string);
		if (matcher.find()) {
			return Integer.parseInt(matcher.group());
		}
		return null;
	}
	
}
Edited by Botre

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...