正则表达式捕获第一个可选字符串之前的所有内容 [英] Regex to capture everything before first optional string
本文介绍了正则表达式捕获第一个可选字符串之前的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想捕获一个模式,但不包括带有preg_match的其他可选模式的第一个实例,例如:
I want to capture a pattern upto but not including the first instance of an optional other pattern with preg_match, eg:
ABCDEFGwTW$% | capture ABCD
@Q%HG@H%hg afdgwsa g weg#D DEFG | capture @Q%HG@H%hg afdgwsa g weg#D D
@Q%HDEFG@H%hg afdgwsa g weg#D DEFG | capture @Q%HD
因此,在上述情况下,将捕获字符串EFG
的第一个实例之前的所有内容.另外,如果EFG
字符串不存在,那么我想捕获整个字符串.
So in the above case anything before the first instance of the string EFG
is captured. also, if the EFG
string is not present then I want to capture the whole string.
我本以为以下方法会奏效,但运气不好:
I would have thought that the following would work, but no such luck:
$pattern = '/(.*)(?:EFG)?/';
preg_match($pattern, 'Q$TQ@#%GEFGw35hqb', $matches);
print_r($matches);
//should give: 'Q$TQ@#%G'
推荐答案
您可以使用
'/(.*?)(?=EFG|$)/'
这篇关于正则表达式捕获第一个可选字符串之前的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文