Here's a utility method with a corresponding test class
/**
* @param input string that contains any number
*
* @return first digits found in string, null if input blank, found no match or too large for integer
*/
public static Integer getInteger(String input){
if(String.isEmpty(input)){
return null;
}
Matcher matcher = Pattern.compile('\\d+').matcher(input);
if(matcher.find()){
try {
return Integer.valueOf(matcher.group(0));
} catch(Exception e){
System.debug(LoggingLevel.ERROR, e);
return null;
}
} else {
return null;
}
}
Test
@IsTest
static void getInteger(){
System.assertEquals(
1234567890,
Strings.getInteger('foo 1234567890')
);
System.assertEquals(
200,
Strings.getInteger('-200')
);
System.assertEquals(
1234567890,
Strings.getInteger('1234567890 foo')
);
System.assertEquals(
1234567890,
Strings.getInteger('1234567890')
);
System.assertEquals(
1234567890,
Strings.getInteger('1234567890.321')
);
System.assertEquals(
1234567890,
Strings.getInteger(' 1234567890 ')
);
System.assertEquals(
1234567890,
Strings.getInteger('baz 1234567890 foo 321')
);
System.assertEquals(
null,
Strings.getInteger('baz 1234567890123456789012345678901234567890')
);
System.assertEquals(
null,
Strings.getInteger('give potato')
);
System.assertEquals(
null,
Strings.getInteger('')
);
System.assertEquals(
null,
Strings.getInteger(null)
);
}