访问量: 10 次浏览
在 Python 中,正则表达式是一组字符,允许您使用搜索模式来查找字符串或一组字符串。RegEx 是正则表达式的术语。
要在 Python 中使用正则表达式,请使用 re 包。
要使用正则表达式在 Python 中匹配字符串开头,我们使用 ^\w+ 正则表达式。
这里:
^:表示以...开头\w:返回匹配包含任何单词字符的字符串(a-z、A-Z、0-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
现在让我们使用 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']