详解Python re.fullmatch.string函数:返回搜索的字符串

  • Post category:Python

我来详细讲解 Python 的 re 模块 re.fullmatch.string 函数的作用与使用方法的完整攻略。

re.fullmatch.string 函数的作用

re.fullmatch.string 函数的作用是在一个字符串中尝试匹配一个正则表达式,如果能够完全匹配,则返回一个匹配对象,否则返回 None。

re.fullmatch.string 函数的使用方法

re.fullmatch.string 函数的基本用法如下:

re.fullmatch(pattern, string, flags=0)

其中,pattern 为要匹配的正则表达式,string 为要匹配的字符串,flags 为匹配模式。

下面是一个具体的实例:

import re

pattern = r'\d+'
string = '12345'

match_obj = re.fullmatch(pattern, string)

if match_obj:
    print(match_obj.group())
else:
    print('匹配失败')

输出结果为:

12345

在上面的实例中,我们定义了一个正则表达式 r'\d+',它匹配一个或多个数字。然后我们将要匹配的字符串设置为 '12345',并使用 re.fullmatch.string 函数进行匹配。由于字符串完全匹配了正则表达式,因此匹配成功,函数返回了一个匹配对象。我们可以使用 match_obj.group() 方法来获取匹配的字符串。

下面再给出一个复杂一些的实例:

import re

pattern = r'^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$'
string1 = 'test@example.com'
string2 = 'test_123@example_cn.com'
string3 = 'test123@abc'

match_obj1 = re.fullmatch(pattern, string1)
match_obj2 = re.fullmatch(pattern, string2)
match_obj3 = re.fullmatch(pattern, string3)

if match_obj1:
    print(match_obj1.group())
else:
    print('字符串 "%s" 不符合要求' % string1)

if match_obj2:
    print(match_obj2.group())
else:
    print('字符串 "%s" 不符合要求' % string2)

if match_obj3:
    print(match_obj3.group())
else:
    print('字符串 "%s" 不符合要求' % string3)

输出结果为:

test@example.com
字符串 "test_123@example_cn.com" 不符合要求
字符串 "test123@abc" 不符合要求

在上面的实例中,我们定义了一个正则表达式,用于匹配符合邮箱格式的字符串。然后我们分别对三个字符串进行了匹配,只有第一个字符串符合要求,因此只有第一个字符串返回了匹配对象,另外两个字符串返回了 None。

这就是 re.fullmatch.string 函数的基本用法,通过对需要匹配的字符串和正则表达式的设置,我们可以方便地将其应用于对各种类型文本的匹配与提取。