</pre><pre name="code" class="java">import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestZhengZe {
public static void main(String[] args) {
//匹配数字
Pattern mac = Pattern.compile("-?(0|([1-9][0-9]*))(\\.[0-9]+)?");
System.out.println(mac.matcher("101.001").matches());
System.out.println(mac.matcher("-00.000").matches());
//截取字符串中的数字和将数字括起来
Pattern pattern = Pattern.compile("[0-9]+");
String s = "aa123cc001qwe";
StringBuilder newStr = new StringBuilder(s);
Matcher matcher = pattern.matcher(s);
int i = 0;
while(matcher.find()){
int start = matcher.start();
int end = matcher.end();
System.out.println(s.substring(start, end));
newStr.insert(start+i, '[');
newStr.insert(end+1+i, ']');
i = i + 2;
System.out.println(newStr.toString());
}
//替换指定的字符串
Pattern patt = Pattern.compile("[a-z]+");
String ss = "1321ase45212zxB11NBV1";
Matcher match = patt.matcher(ss);
ss = match.replaceAll("*");
System.out.println(ss);
//split分割字符串
Pattern pa = Pattern.compile("[A-Z]+");
String[] strArrays = pa.split("123ZAS321ZZ222");
for(String st:strArrays){
System.out.println(st);
}
}
}
结果:
<img src="https://img-blog.csdn.net/20160601162029351?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />