整理自B站 廖雪峰老師的正則運算式課程,
正則運算式的概述
什么是正則運算式?
正則運算式可以用字串來描述規則,并用來匹配字串,
正則運算式是字串,
用字符描述規則,匹配字符,
用正則運算式的好處:
一個正則運算式就是一個描述規則的字串,
只需要撰寫正確的規則,就可以讓正則運算式引擎去判斷目標字串是否符合規則,
正則運算式是一套標準,可以用于任何語言,
jdk的內置正則運算式引擎:java.util.regex
匹配方向:
從左到右按規則匹配
匹配規則:
&:精確匹配:“a\&c” 精確匹配ac
用. 來匹配任意一個字符, “a.c” abc aac acc等
\d: 來匹配數字: “00\d”
\w :可以匹配一個字母,數字或下劃線:“java\w” 不能匹配#和空格,
\s: 可以匹配一個空格字符,“a\sb”
\D:可以匹配任意一個非數字的符號(包括#),”00\D”
\W: 非字母,數字下劃線;“java\w” 可能是 java_
\S: 可以匹配一個非空白字符:”A\SB“ 可以是A&B ABB 不能是”A B“
*: 可以匹配任意0次或多次字符
+:可以匹配至少1字符,
?: 可以匹配零個或一個字符,“A?B” 可以是A和B的任意字符,
{n} : 表示匹配n個字符,”\d{6}” 匹配6個數字
{n,m}:表示匹配n到m個字符,“\d{3,5}”表示匹配3到5個數字
{n,}:至少n個字符,
復雜的匹配規則:
加上^(開頭)和$(結尾)會變得嚴謹,java默認只能做單行匹配,可以不加,
[…]可以匹配范圍內的字符:”[abc]1” 表示abc中的一個 a1 b1 c1;
[a-f]1 表出a到f中的一個和1結合;[a-f0-9_]{6} 下劃線和字母數字間沒有順序
[^…]:匹配[…]內除外的所有字符
AB|CD: AB或CD
learn\s(AB|CD): learn (空格)AB或者learn (空格)CD
案例:匹配5到10位的qq號
public static boolean isValidQQ(String s){
return s.matches("^[1-9]\\d{4,9}$");
}
分組匹配規則
(…)可以用來分組:


String.matches vs Pattern.mather
實際上是一樣的,string的matches內部呼叫的就是pattern.mather
反復使用一個正則運算式進行快速匹配效率低下
可以把正則運算式字串編譯成pattern物件
Pattern pattern = Pattern.compile("^\\d{3,4}\\-\\d{6,8}$");
pattern.mather("010-12345678").matches(); //true
//獲取Match的物件:
Matcher matcher = Pattern.matcher(String s);
matcher.matches(); //true or false
使用Matcher.group(n)快速提取子串

String s = "010-123456";
Pattern pattern = Pattern.compile("^(0\\d{2,3})-([1-9]\\d{5,7})");
Matcher matcher = pattern.matcher(s);
if(matcher.matches()){
String s0=matcher.group(0); //表示獲取全部字符,
String s1=matcher.group(1);
String s2=matcher.group(2);
System.out.println(s1);
System.out.println(s2);
}
貪婪匹配和非貪婪匹配
正則運算式的貪婪匹配
默認是貪婪匹配,就是在匹配時盡可能多地向后匹配,

非貪婪匹配

String s="9999";
Pattern pattern = Pattern.compile("^(\\d??)(9*)$");
Matcher m = pattern.matcher(s);
if(m.matches()){
String s1 = m.group(1);
String s2 = m.group(2);
System.out.println(s1);
System.out.println(s2);
}
提取,搜索及替換
提取的例子
String[] String.split(String regex);
String s = "a#b;;c, 1234;5;";
String[] str = s.split("[\\,\\#\\s+\\;]+");
for (String s1 : str) {
System.out.println(s1);
搜索的例子
Matcher.find();
public static void main(String[] args) {
String s = "the good things hello";
Pattern p = Pattern.compile("the",Pattern.CASE_INSENSITIVE); //忽略大小寫
\\ \\w+ 提取每一個單詞 \\w*o\\w* 帶有o的單詞
Matcher m = p.matcher(s);
while (m.find()){
String sub = s.substring(m.start(),m.end());
System.out.println(sub);
}
}
替換
String.replaceAll();
public static void main(String[] args) {
String s = "the quick brown fox jumps over the lazy dog.";
String s1 = s.replaceAll("\\s+", " ");
System.out.println(s1);
//再將s1的內容加粗體處理
String s2 = s1.replaceAll("(\\w+)", "<b>$1</b>");
System.out.println(s2);
}
本文來自博客園,作者:stack0verflow,轉載請注明原文鏈接:https://www.cnblogs.com/stack0verflow/p/17086450.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/542866.html
標籤:其他
