zoukankan      html  css  js  c++  java
  • 正则表达式(1)

    正则表达式符号与方法一常用符号
    字符 含义
    . 匹配任意字符
    * 匹配一个字符无限次或零次
    ? 匹配一个字符0次或一次
    .* 贪心算法
    .*? 非贪心算法
    () 括号内的结果作为反回值
    常用方法

    在这里插入图片描述
    几种符号的demo

    demo1:
    code = 'huasdakxxIxxbcjkxxlovexxsbsxxyouxxhjhh'
    r = re.findall('..x..', code)
    print(r)
    >>>['akxxI', 'jkxxl', 'vexxs', 'bsxxy', 'ouxxh'] 
    
    demo2:
    code = 'huasdakxxIxxbcjkxxlovexxsbsxxyouxxhjhh'
    r = re.findall('x*', code)
    print(r)
    >>>['', '', '', '', '', '', '', 'xx', '', 'xx', '', '', '', '', 'xx', '', '', '', '', 'xx', '', '', '', 'xx', '', '', '', 'xx', '', '', '', '', '']
    
    demo3:
    code = 'huasdakxxIxxbcjkxxlovexxsbsxxyouxxhjhh'
    r = re.findall('x?', code)
    print(r)
    >>>['', '', '', '', '', '', '', 'x', 'x', '', 'x', 'x', '', '', '', '', 'x', 'x', '', '', '', '', 'x', 'x', '', '', '', 'x', 'x', '', '', '', 'x', 'x', '', '', '', '', '']
    
    demo4:贪心算法
    code = 'huasdakxxIxxbcjkxxlovexxsbsxxyouxxhjhh'
    r = re.findall('xx.*xx', code)
    print(r)
    >>>['xxIxxbcjkxxlovexxsbsxxyouxx']
    
    demo5:非贪心算法
    code = 'huasdakxxIxxbcjkxxlovexxsbsxxyouxxhjhh'
    r = re.findall('xx.*?xx', code)
    print(r)
    >>>['xxIxx', 'xxlovexx', 'xxyouxx']
    
    demo6:括号提取
    code = 'huasdakxxIxxbcjkxxlovexxsbsxxyouxxhjhh'
    r = re.findall('xx(.*?)xx', code)
    print(r)
    >>>['I', 'love', 'you']
    

    re.S使.可以匹配任意字符,包括换行符

    demo1:
    code = '''sdfxxhello
    xxfSdfxxworldxxasdf
    '''
    r = re.findall('xx(.*?)xx', code)
    print(r)
    >>>['fSdf']
    
    demo2:
    code = '''sdfxxhello
    xxfSdfxxworldxxasdf
    '''
    r = re.findall('xx(.*?)xx', code, re.S)
    print(r)
    >>>['hello
    ', 'world']
    
    d+ 匹配纯数字
    code = 'sdcs1234cbs5678dk'
    r= re.findall('d+', code)
    print(r)
    >>>['1234', '5678']
    

    sub

    语法:
    re.sub(pattern, repl, string, count=0, flags=0)

    pattern : 正则中的模式字符串。
    repl : 替换的字符串,也可为一个函数。
    string : 要被查找替换的原始字符串。
    count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。

  • 相关阅读:
    [LeetCode] 456. 132 Pattern
    [LeetCode] 606. Construct String from Binary Tree
    [LeetCode] 536. Construct Binary Tree from String
    [LeetCode] 925. Long Pressed Name
    [LeetCode] 652. Find Duplicate Subtrees
    [LeetCode] 743. Network Delay Time
    [LeetCode] 1209. Remove All Adjacent Duplicates in String II
    [LeetCode] 1047. Remove All Adjacent Duplicates In String
    [LeetCode] 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
    [LeetCode] 859. Buddy Strings
  • 原文地址:https://www.cnblogs.com/l0nmar/p/12553860.html
Copyright © 2011-2022 走看看