如何在Python中使用正则表达式匹配字符串末尾? | 您所在的位置:网站首页 › 怎么提取字符串任意字符python › 如何在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然后,我们使用从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()) 输出执行上述程序后,将获得以下输出。 skills 使用re.findall()方法在Python中的方法 findall(pattern,string) 用于在字符串中定位模式的每个出现。美元符号()确保只在使用模式“\w+ $ ”时匹配字符串末尾的单词。 示例 import re text = 'tutorialspoint is a great platform to enhance your skills' result = re.findall(r'\w+$', text) print(result) 输出以下是上述代码的输出结果。 ['skills'] |
CopyRight 2018-2019 实验室设备网 版权所有 |