python - 需要有关以空格开头的正则表达式的帮助

标签 python regex

我希望字符串以“shivam”开头(不带引号)。我的正则表达式是:(?=shivam\s)\w+ 但在 shivam 之后它们与空间不匹配我该怎么办?

输入为:

shivam gupta

预期输出是:

gupta

两边没有任何空格。我的输出是 shivam gupta

最佳答案

如果你想学习一些正则表达式的使用

import re
s = "shivam gupta"
m = re.match(r"shivam\s+(\w+)$", s)
if m:                 # Check if the pattern matches the string
    print(m.group(1)) # print only Group 1 contents

请参阅Python demo

re.match 方法仅在字符串的开头搜索,因此在开头查找 shivam。然后 \s+ 匹配一个或多个空格,最后,(\w+)$ 匹配 并将一个或多个单词字符捕获到第 1 组中,并且然后是字符串 $ 的结尾。

第 1 组内容通过匹配对象的 .group(1) 访问(此处为 m)。

但是,您可以在此处使用字符串方法和拆分操作:

s = "shivam gupta"
if s.startswith("shivam "):
    print(s.split()[1])    # or even print(s[s.find(" "):])

Another demo .

关于python - 需要有关以空格开头的正则表达式的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40453872/

相关文章:

Python Plotly : Percentage Axis Formatter

python - 用python实现二进制搜索

python - 沿 x 轴在所需距离处的 seaborn 箱线图

python - Jupyter 排序错误

javascript - 找到某个类并返回它

html - 将正则表达式 BBcode 模式转换为 HTML 正则表达式

python - 捕获的异常是无

objective-c - 正则表达式仅在特定字符串之后匹配

c++ - Boost Regex 提供空白捕获

regex - 正则表达式根据单词组合过滤行