简体   繁体   中英

Get pattern text that is within search string

I'm trying to do what I presume to be a simple regex query. In the example below, I'm trying to find all text between the word 'adverb', and 'verb'. The output I get is 'verb' , I reckon that this is a result of the text 'verb' being in 'adverb'.

re.search(r'adverb.+noun|\bverb', 'adverb with text verb text from here on')

My question is how the heck do I get the text I require here? And as you can tell, I need to cater for multiple endstring words.

If it makes a difference, I'm using Python 2.7.

Your regex should be something like this:

You can use re.search() ofcourse..

import re
string = 'adverb with text verb text from here on'
print re.findall(r'adverb(.*?)verb', string)

And it prints out this:

# [' with text ']

EDITED:

If you want to get noun as well, use this:

import re
string = [
    'adverb with text verb text from here on',
    'adverb with text noun text from here on'
]
print [re.findall(r'adverb(.*?)(?:verb|noun)', s) for s in string]

And now you have:

# [[' with text '], [' with text ']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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