1、邮件规则
@Test
/*
* 测试电子邮件规则
* 1、@符
* 2、@符前有一个以上的单词字符
* 3、@符合后有一个.符合
* 4、@和.符号之间包含一个到多个单词字符
* 5、.符号之间包含一个到多个单词字符
* 6、后面还可能重复若干单词
* aaa@sdf.com.cn
* 34545@qq.com.cn.cc
* * \w 匹配所有字符== [a-zA-Z0-9]
* String regx ="[a-zA-Z0-9]+"; 匹配 一次-多次
*/
public void Test1() {
String regex ="\\w+@\\w+(\\.\\w+)+";
String str1= "aaa@sdf.com.cn";
String str2="34545@qq.com.cn.cc";
System.out.println(str1.matches(regex));
System.out.println(str2.matches(regex));
}
2、注释规则
@Test
public void test3() {
Scanner s = new Scanner(System.in);
StringBuffer sb = new StringBuffer();
sb.append("/*这是一个主函数*/\n")//.append("\n")
.append("void main() {\n")
.append("int a = 20; //声明一个变量a\n")
.append("int b = 90; //声明一个变量b\n")
.append("printf(\"a+b=%d\",a+b);\n")
.append("}\n");
/*String temp;
while(!(temp=s.nextLine()).equals("quit")){
sb.append(temp).append("\n");
}*/
String str = sb.toString();
System.out.println(str);
String regx = "\\/\\*.+?\\*\\/";
str=str.replaceAll(regx, "");
//System.out.println(str);
regx = "\\/\\/.+?\\n";
System.out.println(str.replaceAll(regx, "\n"));
}
3、模式匹配
@Test
/*
*
*/
public void test6() {
Pattern pattern =Pattern.compile("(%)(.*?)(%)");
String str = "%sbdddbfzh% %vgvcyvu% %ugbh%";
Matcher m = pattern.matcher(str);
int i=0;
while(m.find()) {
//i++;
System.out.println(m.group(2) + " startIndex:" + m.start() + " ,endIndex:" + m.end());
}
}
4、字符替换
@Test
/*
* str.replace("_", " ") 只能替换一个字符
* replaceAll
*/
public void test2() {
String str = "Hello_World!|hi-Every,One";
//String str = "Hello_World!";
//System.out.println(str.replace("_", " "));
StringBuffer sb = new StringBuffer();
sb.append("_");
System.out.println(str.replace(sb, " "));
System.out.println(str.replaceAll("_|\\||\\-|\\,", " "));
}