zoukankan      html  css  js  c++  java
  • re正则表达式7_{}

    curly brackets {}

    instead of one number, you can specify a range by writing a minimum,a comma,and a maximum in between the curly brackets.

    for example, the regex (ha) {3,5} will match 'hahaha' ,'hahahaha',and 'hahahahaha'

    {3,5}是索引范围,3表示最小值,5表示最大值。

    (ha){3}  =(ha)(ha)(ha)

    (ha){3,5}=

    ((ha)(ha)(ha)|(ha)(ha)(ha)(ha)|(ha)(ha)(ha)(ha)(ha))

    # -*- coding: utf-8 -*-
    """
    Spyder Editor

    This is a temporary script file.
    """
    import re
    #{3}表示倍数
    re1=re.compile(r'(ha){3}')
    mo1=re1.search('hahaha')
    print("mo1.group():",mo1.group())

    #此处找不到匹配的一个ha
    mo2=re1.search('ha')
    mo2==None

    greedy_re=re.compile(r'(ha){3,5}')
    greedy_mo=greedy_re.search('hahahahaha') #五个ha可以匹配3个,4个或5个,贪婪搜索抓取最长的字符串
    print("greedy_mo.group():",greedy_mo.group())

    nonegreedy_re=re.compile(r'(ha){3,5}?')
    nonegreedy_mo=nonegreedy_re.search('hahahahaha')
    print("nonegreedy_mo.group():",nonegreedy_mo.group())

    贪婪与非贪婪搜索

    Python默认使用贪婪搜索,贪婪搜索意味着匹配最长的字符串。

    非贪婪式搜索意味着匹配最短字符串。{}?表示非贪婪搜索

    ?在re正则表达式中有两个意思:

    (1)非贪婪搜索

    (2)flagging an optional group

  • 相关阅读:
    typedef的用法
    重定向在网络编程中的理解
    简答的理解C语言中的各种类型函数
    栈、堆、静态存储区
    标识符起作用范围----作用域、连接类型、存储期
    main函数的argc和argv
    基本数据类型
    数组与指针
    第一章 CLR的执行模型
    Revit 二次开发 沿弧形路径创建拉伸屋顶
  • 原文地址:https://www.cnblogs.com/webRobot/p/5207614.html
Copyright © 2011-2022 走看看