java is based on the regular extraction of Numbers in strings [for example extraction of verification codes in SMS]

  • 2020-06-01 09:54:11
  • OfStack

This article illustrates the example of java's ability to extract Numbers from strings based on the regular. I will share it with you for your reference as follows:

Using Java regex makes it easy to extract qualified content from a string.

1. Extract all phone Numbers in the string:

private void getPhoneNum(String smsBody) {
    Pattern pattern = Pattern.compile("(13|14|15|18)\\d{9}");
    Matcher matcher = pattern.matcher(smsBody);
    while (matcher.find()) {

2. In the development of Android, it is sometimes necessary to extract the verification code (6 digits) in SMS:

private String getYzmFromSms(String smsBody) {
    Pattern pattern = Pattern.compile("\\d{6}");
    Matcher matcher = pattern.matcher(smsBody);
    if (matcher.find()) {
    return null;

PS: here are two more handy regular expression tools for you to use:

JavaScript regular expression online testing tool:

Online regular expression generation tool:

I hope this article has been helpful to you in java programming.

Related articles: