自动化测试(二)python-正则表达式(re)

79 阅读1分钟

常用函数:

1. re.match()

  • 功能:从字符串的起始位置开始匹配,如果起始位置不匹配,则返回 None

  • 特点:要求匹配必须从字符串的第一个字符开始。

    import re
    pattern = r'hello'
    string = 'hello world'
    match = re.match(pattern, string)
    print(match)  # 输出: <re.Match object; span=(0, 5), match='hello'>
    

2. re.search()

  • 功能:扫描整个字符串,返回第一个匹配的位置,如果没有找到匹配,则返回 None

  • 特点:可以在字符串的任意位置进行匹配。

    import re
    pattern = r'world'
    string = 'hello world'
    match = re.search(pattern, string)
    print(match) # 输出: <re.Match object; span=(6, 11), match='world'>
    

3. re.findall()

  • 功能:返回所有匹配项的列表。

  • 特点:返回的是一个列表,包含所有非重叠的匹配结果。

    import re
    pattern = r'\d+'
    string = '123 abc 456 def 789'
    matches = re.findall(pattern, string)
    print(matches)  # 输出: ['123', '456', '789']
    

Match 对象方法及其使用示例:

1. group()

  • 功能:返回整个匹配项或指定组的匹配内容。

  • 参数:可以传入组号或组名(对于命名组),默认返回整个匹配项。

    import re
    pattern = r'(\d{3})-(\d{2})-(\d{4})'
    string = 'My SSN is 123-45-6789'
    match = re.match(pattern, string)
    if match:
        print(match.group())    # 输出: 123-45-6789
        print(match.group(1))   # 输出: 123
        print(match.group(2))   # 输出: 45
        print(match.group(3))   # 输出: 6789
    

2. groups()

  • 功能:返回所有捕获组的元组。

    import re
    pattern = r'(\d{3})-(\d{2})-(\d{4})'
    string = 'My SSN is 123-45-6789'
    match = re.match(pattern, string)
    if match:
        print(match.groups())  # 输出: ('123', '45', '6789')