最近项目需要,要把一行字符串里面的电话号码识别出来,并且转换成可以直接在手机上拨打连接。用正则写了一个,初步测试好像能用。记下来,有用的时候可以用用。
直接代码:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Master
*
*/
public class TelNoUtil
{
private static final int MIN_TELNO_LEN = 3;
//识别电话号码
public static List<String> parseTelNo(String str)
{
List<String> telNo = new ArrayList<String>();
String strNo = null;
if(null == str || str.length() <= 0) {
return telNo;
}
Pattern p = Pattern.compile("(\\(?\\d+\\)?\\-?)?\\d+(\\-?\\d+)*");
Matcher m = p.matcher(str);
while (m.find()) {
strNo = m.group();
if(strNo.length() >= MIN_TELNO_LEN) {
telNo.add(m.group());
}
}
return telNo;
}
//将识别出来的电话号码处理为一个只有数字的号码
public static String parseTelNoToDail(String strTelNo)
{
StringBuffer sbrDailNo = new StringBuffer();
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(strTelNo);
while (m.find()) {
sbrDailNo.append(m.group());
}
return sbrDailNo.toString();
}
//将识别出来的电话号码生成为一个拨打链接
public static String telNoToLink(String strTelString)
{
StringBuffer sbrTelLink = new StringBuffer();
if(null != strTelString && strTelString.length()>0) {
sbrTelLink.append("<a ");
sbrTelLink.append("href=\"tel:");
sbrTelLink.append(parseTelNoToDail(strTelString));
sbrTelLink.append("\">");
sbrTelLink.append(XmlString.CheckReservedString(strTelString));
sbrTelLink.append("</a>");
}
return sbrTelLink.toString();
}
//直接调用的函数,将字符串中电话号码替换成TEL链接
public static String detectionTelNo(String str)
{
List<String> telNo = parseTelNo(str);
for(String strTelNo:telNo){
System.out.println(strTelNo);
str = str.replace(strTelNo, telNoToLink(strTelNo));
}
return str;
}
}