Home  >  Article  >  Java  >  Java uses regular expressions to extract numbers from strings [such as extracting verification codes from text messages]

Java uses regular expressions to extract numbers from strings [such as extracting verification codes from text messages]

高洛峰
高洛峰Original
2017-02-03 17:13:081562browse

本文实例讲述了java基于正则提取字符串中的数字功能。分享给大家供大家参考,具体如下:

使用Java正则可以很方便的从字符串中提取符合条件的内容。

1.提取字符串中所有的手机号:

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

   

2.在Android开发中,有时候需要提取短信中的验证码(6位数字):

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

   

更多java基于正则提取字符串中的数字功能【如提取短信中的验证码】相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:java fine-grained lockNext article:java fine-grained lock