Extracting digits from a string

1- Done the “Old Way”

String message = "AB 12DCEF";

StringBuffer result = new StringBuffer();

int len = message.length();

for (int i=0; i<len; i++) {

	Character c = message.charAt(i);

	if (Character.isDigit(c)) result.append(c);


System.out.println (result); // = 12

2- With Regular expressions (regexp)

String message = "AB 12DCEF";

String format ="\\d+";

Pattern pattern = Pattern.compile(format);

Matcher matcher = pattern.matcher(message);

if (matcher.find()) {

	System.out.println ( matcher.group()); // =12


One thought on “Extracting digits from a string

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s