Java使用正则匹配
整理一下正则表达式再Java中的使用
1.Java trim() 方法
删除头尾空白符的字符串。
public class Test {
public static void main(String args[]) {
String Str = new String(" www.runoob.com ");
System.out.print("原始值 :" );
System.out.println( Str );
System.out.print("删除头尾空白 :" );
System.out.println( Str.trim() );
}
}
==>原始值 : www.runoob.com
==>删除头尾空白 :www.runoob.com
2.匹配空格(一个或多个)
正则:String regEx = “[’ ']+”;
// 匹配空格,可以替换成其它
@Test
public void test2() {
String s ="a b a a ";
String regEx = "[' ']+";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(s);
System.out.println(m.replaceAll("").trim());
}
==>abaa
3.匹配回车换行
1.我一般都是直接切割,再对每一行进行处理
String[] allContent = description.split("\n");
// An highlighted block
var foo = 'bar';
4.匹配字符串
正则匹配字符串
Pattern p = Pattern.compile(expression); // 正则表达式
Matcher m = p.matcher(str); // 操作的字符串
boolean b = m.matches(); //返回是否匹配的结果
System.out.println(b);
Pattern p = Pattern.compile(expression); // 正则表达式
Matcher m = p.matcher(str); // 操作的字符串
boolean b = m.lookingAt (); //返回是否匹配的结果
System.out.println(b);
Pattern p = Pattern.compile(expression); // 正则表达式
Matcher m = p.matcher(str); // 操作的字符串
boolean b = m.find (); //返回是否匹配的结果
System.out.println(b);
切割字符串
Pattern pattern = Pattern.compile(expression); //正则表达式
String[] strs = pattern.split(str); //操作字符串 得到返回的字符串数组
替换字符串
Pattern p = Pattern.compile(expression); // 正则表达式
Matcher m = p.matcher(text); // 操作的字符串
String s = m.replaceAll(str); //替换后的字符串
查找输出字符串
Pattern p = Pattern.compile(expression); // 正则表达式
Matcher m = p.matcher(text); // 操作的字符串
while (m.find()) {
matcher.start() ;
matcher.end();
matcher.group(1);
}
查找替换指定字符串
Pattern p = Pattern.compile(expression); // 正则表达式
Matcher m = p.matcher(text); // 操作的字符串
StringBuffer sb = new StringBuffer();
int i = 0;
while (m.find()) {
m.appendReplacement(sb, str);
i++; //字符串出现次数
}
m.appendTail(sb); //从截取点将后面的字符串接上
String s = sb.toString();