Jump to content

[Snippet] Extract integers from a message


Botre

Recommended Posts

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
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

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