2016/5/22

来源:互联网 发布:伊登软件股份有限公司 编辑:程序博客网 时间:2024/06/05 13:33
关于正则表达式:
正则表达式在java.uti.regx中




String的判断是否匹配用matches();方法,返回的是一个boolean
"abc".matches("...");======结果是true(一个.表示一个字符)




"a237928a".replaceAll("\\d","-");把字符串中所有的数字用-代替其中"\\d"是一个正则表达式,\d代表一个数字\代表转义。




Pattern类:compile();函数是提前编译一个匹配模式,用这个模式区匹配字符串速度会更快:
Pattern p = Pattern.compile("[a-z](3)");
Matcher m = p.matcher("akhak");//传入的是字符序列,返回的是一个Matcher.里面是匹配的结果
m.matches();返回一个boolean 表示匹配还是不匹配。
"a".matches("[abc]");//和abc里面的某一个匹配  true;








写一个正则表达式好了:
import java.util.regex.*;


public class StringUtils {
public static void main(String[] arge){
StringUtils s = new StringUtils();
String s1 = "0xA";
s.fixedTests(s1);
}
 public void fixedTests(String s1) {
   boolean b = StringUtilsTest.isHexNumber("0x");
   System.out.println(b);
 }
}




class StringUtilsTest {
  
  public static boolean isHexNumber(String s) {
    boolean isMatch = s.matches("^0x[a-fA-F0-9]+");
    return isMatch;
  }
}






但是这种写法更好一点:
import java.util.*;
import java.util.regex.*;


public class StringUtils {
public static void main(String[] arge){
StringUtils s = new StringUtils();
String s1 = null;
Scanner in = new Scanner(System.in);
s1 = in.next();
s.fixedTests(s1);
}
 public void fixedTests(String s1) {
   boolean b = StringUtilsTest.isHexNumber(s1);
   System.out.println(b);
 }
}




class StringUtilsTest {
  
  public static boolean isHexNumber(String s) {
 Pattern p = Pattern.compile("^0x[a-fA-F0-9]+");
 Matcher matcher = p.matcher(s);
    boolean isMatch = matcher.matches();
    return isMatch;
  }
}









0 0