正则表达式基本语法总结

总结最常用的一些语法

目录

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值