Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to capture everything before first optional string

Tags:

regex

php

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

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'
like image 219
mulllhausen Avatar asked May 12 '11 14:05

mulllhausen


People also ask

How do you match everything except with regex?

How do you ignore something in regex? To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.

Which regex special characters match the start of a string?

The position anchors ^ and $ match the beginning and the ending of the input string, respectively. That is, this regex shall match the entire input string, instead of a part of the input string (substring). \w+ matches 1 or more word characters (same as [a-zA-Z0-9_]+ ).

Does order matter in regex?

The order of the characters inside a character class does not matter. The results are identical. You can use a hyphen inside a character class to specify a range of characters. [0-9] matches a single digit between 0 and 9.


2 Answers

You can use

'/(.*?)(?=EFG|$)/'
like image 117
Jens Avatar answered Sep 17 '22 16:09

Jens


Try this: (.*?)(?:EFG|$)

This will match any character (as few as possible) until it finds EFG.

like image 23
Josh M. Avatar answered Sep 20 '22 16:09

Josh M.