天天看点

Android开发(21)使用正则表达式需求步骤代码

需求

在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;
}

}           

复制