简体   繁体   English

在python 3.x中使用正则表达式来抓取字符串的一部分

[英]Grabbing a part of a string using regex in python 3.x

So what i am trying to do is to have an input field named a. 所以我想做的是有一个名为a的输入字段。 Then have a line of regex which checks a for 'i am (something)' (note something could be a chain of words.) and then prints How long have you been (something)? 然后有一行正则表达式检查“我是(某物)”(注意某物可能是一连串的单词。),然后打印出您(某物)已有多长时间了?

This is my code so far: 到目前为止,这是我的代码:

if re.findall(r"i am", a):
    print('How long have you been {}'.format(re.findall(r"i am", a)))

But this returns me a list of [i, am] not the (something). 但这会给我返回[i,am]的列表,而不是(某物)。 How do i get it to return me (something?) 我如何得到它回报我(某物?)

Thanks, 谢谢,

A n00b at Python Python上的n00b

Do you mean something like this? 你的意思是这样吗?

>>> import re
>>> a = "I am a programmer"
>>> reg = re.compile(r'I am (.*?)$')
>>> print('How long have you been {}'.format(*reg.findall(a)))
How long have you been a programmer

r'I am (.*?)$' matches I am and then everything else to the end of the string. r'I am (.*?)$'匹配I am ,然后匹配所有其他内容,直到字符串末尾。


To match one word after, you can do: 要匹配一个单词,您可以执行以下操作:

>>> a = "I am an apple"
>>> reg = re.compile(r'I am (\w+).*?$')
>>> print('How long have you been {}'.format(*reg.findall(a)))
How long have you been an

may be just a simple solution avoiding a weigth and cost regexp 可能只是避免重量轻和成本正则表达式的简单解决方案

>>> a = "i am foxmask"
>>> print a[5:]
foxmask

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM