示例一:
示例四:
示例五:
示例六:
/**
* 字符串支持正则表达式做格式验证的方法
* @author Administrator
*
*/
public class StringDemo1 {
public static void main(String[] args) {
/*
* 验证电子邮箱地址的正则表达式
* [a-zA-Z0-9_]+@[a-zA-Z0-9_]+(\.[a-zA-Z0-9]+)+
*/
String regex
= "[a-zA-Z0-9_]+@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9]+)+";
//打桩
System.out.println(regex);
String str = "fancq@tarena.com.cn";
/*
* boolean matches(String regex)
* 判断当前字符串是否满足给定的正则表达式所
* 规定的格式,满足则返回true
* 需要注意的是,无论正则表达式中是否书写了"^ $"
* 都是做全匹配
*/
boolean matches = str.matches(regex);
System.out.println(matches?"是邮箱":"不是邮箱");
}
}
示例二:
/**
* 字符串支持正则表达式的方法2:
* 将字符串中满足正则表达式格式的部分拆分,返回所有
* 剩余部分的内容。
*
* String[] split(String regex)
*
* @author Administrator
*
*/
public class StringDemo2 {
public static void main(String[] args) {
String str = "abd123jlk435g76kljl4534ghjg897asd";
/*
* 需求:切掉所有数字部分,只保留所有英文部分
*
* [0-9]+
*/
String[] array = str.split("[0-9]+");
for(int i=0;i<array.length;i++){
System.out.println(array[i]);
}
}
}
示例三:
/**
* 根据"\"拆分字符串时的情况
* @author Administrator
*
*/
public class StringDemo3 {
public static void main(String[] args) {
String str = "1\\2\\3\\4\\5\\6\\7\\8\\9\\0";
/*
* 1\2\3\4\5\6\7\8\9\0
* 根据"\"拆分字符串。
* 那么用正则表达式表示"\"的话要写成"\\"。
* 那么用java字符串去表示正则表达式中的"\\"就
* 要写成"\\\\"。
*/
System.out.println(str);
String[] array = str.split("\\\\");
for(int i=0;i<array.length;i++){
System.out.println(array[i]);
}
}
}
示例四:
/**
* 拆分字符串的注意事项
* @author Administrator
*
*/
public class StringDemo4 {
public static void main(String[] args) {
String str = "1,2,3,4,5,6,7,,,,,,,,,,,,,,,";
/*
* 如果在字符串中间,连续出现了若干次要拆分的字符
* 那么每一项中间都会拆除一个空字符串。
* 例如: ,,,,,1,2,3,4,5,6,7
* 在1之前,会拆出5个空字符串。
* 只有在字符串末尾连续匹配的话,是不拆出多余的空
* 字符串的!
*/
String[] array = str.split(",");
System.out.println(array.length);
for(int i=0;i<array.length;i++){
System.out.println(array[i]);
}
}
}
示例五:
/**
* split的小例子
* @author Administrator
*
*/
public class StringDemo5 {
public static void main(String[] args) {
String imgName = "2015/04/03.jpg";
String[] array = imgName.split("\\.");
long c = System.currentTimeMillis();
imgName = c+"."+array[1];
System.out.println(imgName);
}
}
示例六:
/**
* java支持正则表达式的方法3:
* 将当前字符串中满足正则表达式的部分替换为给定字符串
*
* String replaceAll(String regex,String str)
*
* @author Administrator
*
*/
public class StringDemo6 {
public static void main(String[] args) {
String str = "fg123fghgf534hgf5675hfhg678asd";
/*
* 将字符串中的数字部分替换为字符串"#NUMBER#"
*
* [0-9]+
*
*/
System.out.println(str);
str = str.replaceAll("[0-9]+", "#NUMBER#");
System.out.println(str);
}
}
示例七:
/**
* replaceAll的应用
* @author Administrator
*
*/
public class StringDemo7 {
public static void main(String[] args) {
String regex
= "(wqnmlgb|cmd|sb|tmd|sob|213|wc|jb|nc)";
String message = "wqnmlgb!你这个nc!你怎么这么sb!cmd!";
message = message.replaceAll(regex, "****");
System.out.println(message);
}
}