總結最常用的一些語法
目錄
1、基本語法
①限定符
? | 零次或一次匹配前面的字符或子表達式,相當於{0,1} |
* | 零次或多次匹配前面字符或子表達式,相當於{0,} |
+ | 一次或多次匹配前面字符或子表達式,相當於{1,} |
{n} | 匹配n次 |
{n,} | 匹配至少n次 |
{n,m} | 匹配n到m次 |
②匹配符
\d | 數字字符匹配,等效於[0-9] |
\D | 非數字字符匹配,等效於[^0-9] |
\w | 匹配任何字類字符,等效於[A-Za-z0-9] |
\W | 匹配任何非字類字符,等效於[^A-Z^a-z^0-9] |
\f | 換頁符匹配 |
\n | 換行符匹配 |
\r | 匹配一個回車符 |
\s | 匹配任何空白字符 |
\S | 匹配任何非空白字符 |
\t | 製表符匹配 |
③判斷符
x|y | 匹配x或y |
[xyz] | 匹配包含的任一字符 |
[^xyz] | 反向匹配,匹配不包含任何字符 |
[a-z] | 匹配指定範圍的任何字符 |
④定位符
^ | 匹配輸入字符串起始位置 |
$ | 匹配輸入字符串結尾位置 |
\b | 匹配字和空格間的位置 |
\B | 非字邊界匹配 |
⑤貪心匹配
當 ? 緊隨任何其他限定符,匹配模式是非貪心的,匹配搜索儘可能短的字符串
默認貪心模式
⑥example
\”(.*?)\”匹配文本中帶雙引號的內容
2、正則的具體用法
2.1、java
在java中主要注意的 \ 的問題,
\ 相當一個 \
\ 匹配 \
\\ 匹配 \
( 匹配 (
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* test0619.java.
* @author Kaiyan Zhang
*
*/
public class test0619 {
public static void main(String [] args) {
String name = "Thomas#Yang";
String regex = "\\w+";
/* 直接匹配 */
boolean matches1 = name.matches(regex);
System.out.println(matches1); //false
/* 構造相關類匹配 */
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(name);
/* 匹配 */
System.out.println(m.matches())
/* 解析-數據結構 */
while(m.find()) {
System.out.println(m.group()); //Line1:Thomas Line2:Yang
}
/* 替換 */
String input = "The <b>Good</b>, the <i>Bad</i>, and the<strong>Ugly</strong>";
String regex1 = "<\\w+>|</\\w+>";
String output = input.replaceAll(regex1, "");
System.out.println(output); /* The Good, the Bad, and theUgly */
}
}
2.2、python
import re
def delete():
'''
re.sub(pattern, repl, string, count=0, flags=0)
pattern 模式字符串
repl 要替換的字符串
string 要被查找替換的原始字符串
count 模式匹配後替換的最大次數,默認0表示替換所有匹配
'''
phonenum = "2004-959-559 #這是一個國外電話號碼"
num = re.sub(r'#.*$',"",phonenum)
print(num)
num = re.sub(r'\D',"",phonenum)
print(num)
def finditer():
'''
re.finditer(pattern, string, flags=0)
'''
it = re.finditer(r"\d+","12zxcv56asfd87ag")
for match in it:
print(match.group())
def findall():
'''
findall(string[,pos[,endpos]])
string 待匹配字符串
pos 指定字符串的起始位置
endpos 指定字符串的結束位置
'''
pattern1 = re.compile(r'\d+')
result1 = pattern1.findall('1232yohu google 999')
pattern2 = re.compile(r'@\w+')
result2 = pattern2.findall('@google and you can also @tecent @apple @oracle',0,30)
print('match \\d+')
for r in result1:
print(r)
print('match @someone')
for r in result2:
print(r)
def split():
'''
按模式分割
re.split(pattern, string[,maxsplit=0,flags=0])
maxsplit最大分割次數
'''
s = re.split('\W+', 'google, apple, amazon, amd, oracle, baidu, alibaba, tecent')
for sp in s:
print(sp)