Home > Java > javaTutorial > 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]

高洛峰
Release: 2017-02-03 17:13:08
Original
1616 people have browsed it

本文实例讲述了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());
    }
}
Copy after login

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;
}
Copy after login

   

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template