首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >regex - Python在前瞻性断言中完全匹配

regex - Python在前瞻性断言中完全匹配
EN

Stack Overflow用户
提问于 2019-02-22 07:41:19
回答 1查看 158关注 0票数 0

如果用户输入变量单词与字符串a中的完全匹配,则我想检索句子的其余部分。

代码语言:javascript
复制
a = 'hello there, I wanted to find out how to split this document'
word = 'wanted'
context = re.search(r'(?=^{user}$)(.*$)'.format(user=word), a)
context.group(0)

目前,我已经尝试放置锚和$以确保其匹配,但它将返回此错误消息。

代码语言:javascript
复制
AttributeError: 'NoneType' object has no attribute 'group'

当我将下面的代码更改为:

代码语言:javascript
复制
a = 'hello there, I wanted to find out how to split this document'
word = 'wanted'
context = re.search(r'(?={user}$)(.*$)'.format(user=word), a)
context.group(0)

任何提示都将不胜感激!谢谢!!

EN

回答 1

Stack Overflow用户

发布于 2019-02-22 07:43:41

没有正则表达式的

代码语言:javascript
复制
a = 'hello there, I wanted to find out how to split this document'
word = 'wanted'

if word in a:
    print(a.split(word,1)[1])

带有regex的(使用字界):

代码语言:javascript
复制
import re
if re.search(r'\b' + word + r'\b', a):
    # print('{0} found'.format(word))
    m = re.search("(?<=" + word + ")(.*)", a)
    print(m.group(0))
else:
    print('{0} not found'.format(word))

产出:

代码语言:javascript
复制
 to find out how to split this document
 to find out how to split this document
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54822266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档