Python ``re`` 模块匹配字符串开头:正则 ^ 符号完整教程


发布日期 : 2019-03-10 17:38:47 UTC

访问量: 10 次浏览

如何在 Python 中使用正则表达式匹配字符串开头

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

要在 Python 中使用正则表达式,请使用 re 包。

要使用正则表达式在 Python 中匹配字符串开头,我们使用 ^\w+ 正则表达式。

这里:

  • ^:表示以...开头
  • \w:返回匹配包含任何单词字符的字符串(a-zA-Z0-9 和下划线字符)
  • +:表示一个或多个字符的出现

使用 re.search() 方法

在以下示例代码中,我们匹配单词 tutorialspoint,该单词出现在字符串 tutorialspoint is a great platform to enhance your skills 的开头。

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

import re

然后使用从 re 模块导入的 search() 函数获取所需的字符串。Python 中的 re.search() 函数在字符串中搜索匹配项,并在有匹配项时返回匹配对象。使用 group() 方法返回匹配的字符串的一部分。

示例

import re

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

输出

tutorialspoint

示例 2

现在让我们使用 Python 中的 re.search() 方法找出字符串的第一个字母:

import re

s = 'Program'
result = re.search(r"\b[a-zA-Z]", s)
print('The first letter of the given string is:', result.group())

输出

The first letter of the given string is: P

使用 re.findall() 方法

Python 中的 findall(pattern, string) 方法能够定位字符串中模式的每一个出现。符号 ^ 确保使用模式 ^\w+ 仅在字符串开头匹配单词
Python

示例

import re

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

输出

字符串 tutorialspoint 出现了两次,但在以下输出中,我们只看到了一处匹配,该匹配出现在字符串开头:

['tutorialspoint']

示例

现在让我们使用 Python 中的 re.findall() 方法查找字符串的第一个字母:

import re

s = '程序'
result = re.findall(r"\b[a-zA-Z]", s)
print('给定字符串的第一个字母为:', result)

输出

给定字符串的第一个字母为: ['P']