需求
在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;
}
}
複制