如何在Python中使用正则表达式匹配字符串末尾?

如何在Python中使用正则表达式匹配字符串末尾?

Python中的正则表达式是一组字符,允许您使用搜索模式来查找字符串或一组字符串。 RegEx是正则表达式的另一个术语。

使用 re 包来处理Python中的正则表达式。

要使用正则表达式匹配Python中的字符串末尾,我们使用以下正则表达式: **^/w+ $ **

这里,

  • ** $ ** 表示以…为结尾。

  • /w 返回与字符串中包含任何单词字符(a-z,A-Z,0-9和下划线字符)相匹配的结果。

  • + 表示字符的一个或多个出现。

阅读更多:Python 教程

使用re.search()方法

在以下示例代码中,我们匹配单词 skills ,它出现在字符串“ tutorialspoint is a great platform to enhance your skills ”的末尾。

我们首先导入正则表达式模块。

import re
Python

然后,我们使用从re模块导入的 search() 函数。此 re.search() 函数在Python中搜索字符串,如果有匹配,则返回匹配对象。使用 group() 方法返回匹配的字符串部分。

示例

import re
s = 'tutorialspoint is a great platform to enhance your skills'
result = re.search(r'\w+$', s)
print(result.group())
Python

输出

执行上述程序后,将获得以下输出。

skills
Python

使用re.findall()方法

在Python中的方法 findall(pattern,string) 用于在字符串中定位模式的每个出现。美元符号(ParseError: KaTeX parse error: Undefined control sequence: \w at position 11: )确保只在使用模式“\̲w̲+ $ ”时匹配字符串末尾的单词。

示例

import re
text = 'tutorialspoint is a great platform to enhance your skills'
result = re.findall(r'\w+$', text)
print(result)
Python

输出

以下是上述代码的输出结果。

['skills']
Python

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册