zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python里使用正则表达式的重复模式

2023-09-14 09:10:35 时间
在前面学习的正则表达式,都是把每一个字符写出来的,但是如果有重复的字符,也需要写出来吗?比如重复1000个字符,这时全写出来就不是很聪明的做法了,那么怎么办呢?可以使用某种规则来生成。如下面的例子:
#python 3. 6
#蔡军生 
#http://blog.csdn.net/caimouse/article/details/51749579
#
import re


def test_patterns(text, patterns):
    """Given source text and a list of patterns, look for
    matches for each pattern within the text and print
    them to stdout.
    """
    # Look for each pattern in the text and print the results
    for pattern, desc in patterns:
        print("'{}' ({})\n".format(pattern, desc))
        print("  '{}'".format(text))
        for match in re.finditer(pattern, text):
            s = match.start()
            e = match.end()
            substr = text[s:e]
            n_backslashes = text[:s].count('\\')
            prefix = '.' * (s + n_backslashes)
            print("  {}'{}'".format(prefix, substr))
        print()
    return


if __name__ == '__main__':
    test_patterns('abbaaabbbbaaaaa',
                  [('ab', "'a' followed by 'b'"),
                   ])
结果输出如下:

'ab' ('a' followed by 'b')


  'abbaaabbbbaaaaa'
  'ab'
  .....'ab'

这个例子的代码是方便来测试不同的正则表达式。

接着来测试一下重复的正则表达式:

#python 3. 6
#蔡军生 
#http://blog.csdn.net/caimouse/article/details/51749579
#
from re_test_patterns import test_patterns

test_patterns(
    'abbaabbba',
    [('ab*', '0个或多个b跟在a后面'),
     ('ab+', '1个或多个b跟在a后面'),
     ('ab?', '0个或1个b跟在a后面'),
     ('ab{3}', '只能3个b跟在a后面'),
     ('ab{2,3}', '2个到3个b跟a后面')],
)
结果输出如下:

'ab*' (0个或多个b跟在a后面)


  'abbaabbba'
  'abb'
  ...'a'
  ....'abbb'
  ........'a'


'ab+' (1个或多个b跟在a后面)


  'abbaabbba'
  'abb'
  ....'abbb'


'ab?' (0个或1个b跟在a后面)


  'abbaabbba'
  'ab'
  ...'a'
  ....'ab'
  ........'a'


'ab{3}' (只能3个b跟在a后面)


  'abbaabbba'
  ....'abbb'


'ab{2,3}' (2个到3个b跟a后面)


  'abbaabbba'
  'abb'
  ....'abbb'

深入浅出Numpy
http://edu.csdn.net/course/detail/6149 

Python游戏开发入门

你也能动手修改C编译器

纸牌游戏开发

http://edu.csdn.net/course/detail/5538 

五子棋游戏开发

http://edu.csdn.net/course/detail/5487
RPG游戏从入门到精通
http://edu.csdn.net/course/detail/5246
WiX安装工具的使用
http://edu.csdn.net/course/detail/5207
俄罗斯方块游戏开发
http://edu.csdn.net/course/detail/5110
boost库入门基础
http://edu.csdn.net/course/detail/5029
Arduino入门基础
http://edu.csdn.net/course/detail/4931
Unity5.x游戏基础入门
http://edu.csdn.net/course/detail/4810
TensorFlow API攻略
http://edu.csdn.net/course/detail/4495
TensorFlow入门基本教程
http://edu.csdn.net/course/detail/4369
C++标准模板库从入门到精通 
http://edu.csdn.net/course/detail/3324
跟老菜鸟学C++
http://edu.csdn.net/course/detail/2901
跟老菜鸟学python
http://edu.csdn.net/course/detail/2592
在VC2015里学会使用tinyxml库
http://edu.csdn.net/course/detail/2590
在Windows下SVN的版本管理与实战 
http://edu.csdn.net/course/detail/2579
Visual Studio 2015开发C++程序的基本使用 
http://edu.csdn.net/course/detail/2570
在VC2015里使用protobuf协议
http://edu.csdn.net/course/detail/2582
在VC2015里学会使用MySQL数据库
http://edu.csdn.net/course/detail/2672