前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android开发(21)使用正则表达式

Android开发(21)使用正则表达式

作者头像
张云飞Vir
发布2020-03-16 15:13:02
4580
发布2020-03-16 15:13:02
举报

需求

在android开发中使用正则

步骤

1.构建正则对象

    Pattern p;
    p = Pattern.compile("\\d{10}");

2.匹配

    Matcher m;
    m = p.matcher(barcodeDesc);//获得匹配

3.查看匹配结果

while(m.find()){ //注意这里,是while不是if
            String xxx = m.group();
            System.out.println("res ="+xxx);
        }

代码

代码中,我想获得多个匹配的结果,第一次错误写法 "if(m.find)",总是只能获得一个匹配的数字。 查了若干资料,无意中读了一段代码才发现这个差别。匹配多个使用 while(m.find)

package com.example.test111;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String res = "";
    String str1 = "1234567890,1234567891";
    
    String str2 = "青云店镇\n1115103001\r北京日杂\n北200米路西\ncpp\n80285135\n农药";
    String str3 = "1234567890\n采育\n1115104004\n大兴\n13661175819\n北京市\n种子、化肥";
    String str4 = "xfdsfds";
    
    res = test(str1);
            
    res = test(str2);
            
    res = test(str3);
            
    res = test(str4);
}

private String test(String barcodeDesc) {
    Pattern p;
    p = Pattern.compile("\\d{10}");//在这里,编译 成一个正则。
    Matcher m;
    m = p.matcher(barcodeDesc);//获得匹配
    String res = "";
    
    while(m.find()){ //注意这里,是while不是if
        String xxx = m.group();
        System.out.println("res ="+xxx);
    }
    return res;
}

}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 需求
  • 步骤
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档