问题
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