Regex match everything from the last occurrence of either keyword

情到浓时终转凉″ 提交于 2019-12-11 03:55:34

问题


I'm trying to match everything from the last occurrence of either keyword (foo or bar) to the end of the string.

Example (a):

// I want to match ' foo do you?';
$source = 'This is foo and this is bar i like foo do you?';
$pattern = '/pattern/';
preg_match($pattern, $source, $matches);

I tried the following:

$pattern = '/( (foo|bar) .*)$/';

Thinking it would match the last occurrence of foo and all the following text, but it instead matches the first occurrence.

print_r($matches);

/*
Array
(
    [0] =>  foo and this is bar i like foo do you?
    [1] =>  foo and this is bar i like foo do you?
    [2] => foo
)
*/

Note I'm concerned with the theory and reasoning of how to do this, so please add some explanation or a link to to the relevant explanation, please.


回答1:


.+((foo|bar).+)$

.+ matches many characters up front.

((foo|bar) matches and captures your keyword(s).

.+) matches and captures many characters.

$ matches the end of the string/line.

Using your example:

This is foo and this is bar i like foo do you?
                                   ^---------^



回答2:


Use a greedy match up front to consume as much of the haystack as you can before your pattern:

>>> import re
>>> source = 'This is foo and this is bar i like foo do you?'
>>> pattern = '.*((?:foo|bar).*)'
>>> re.search(pattern, source).groups()[0]
'foo do you?'

A grottier way of doing it is to use negative look-aheads:

>>> # Negative look-ahead for the pattern: (?!.*(?:foo|bar))
>>> pattern = '((?:foo|bar)(?!.*(?:foo|bar)).*)'
>>> re.search(pattern, source).groups()[0]
'foo do you?'


来源:https://stackoverflow.com/questions/5440194/regex-match-everything-from-the-last-occurrence-of-either-keyword

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!