Reputation: 2415
I am trying to match a string pattern and my regex is
/^[a-zA-Z0-9]*(-|\s)*Iphone 7(\s|-)?(\p{N}GB)?\B/i
And the string with which I am trying to match is Apple Iphone 7 Plus 16 Gb
. I want to match the exact regex i.e. Iphone 7 should only match with following
Please let me know what I am doing wrong? Here is regex link
Upvotes: 0
Views: 94
Reputation: 91385
Not sure to well unsderstand your need, but how about:
/^.*?iphone 7(?:\s+(?:plus\s+)?\d+\s?gb.*)?$/i
Explanation:
/ : regex delimiter
^ : begining of string
.*? : 0 or more any characters not greedy
iphone 7 : literally
(?: : start non capture group
\s+ : 1 or more spaces
(?: : start non capture group
plus : literally
\s+ : 1 or more spaces
)? : end group^, optional
\d+ : 1 or more digits
\s? : 1 optional space
gb : literally
.* : 0 or more any character
)? : end group, optional
$ : end of string
/i : regex delimiter, case insensitive
In action:
$tests = array(
'any digits or string apple iphone 7',
'any digits or string apple iphone 7 16 gb',
'any digits or string apple iphone 7 32GB - Silver',
'any digits or string apple iphone 7 plus',
'any digits or string apple iphone 7s',
);
foreach ($tests as $test) {
echo "$test\t ==> ";
if (preg_match('/^.*?iphone 7(?:\s+(?:plus\s+)?\d+\s?gb.*)?$/i', $test)) {
echo "match\n";
} else {
echo "doesn't match\n";
}
}
Output:
any digits or string apple iphone 7 ==> match
any digits or string apple iphone 7 16 gb ==> match
any digits or string apple iphone 7 32GB - Silver ==> match
any digits or string apple iphone 7 plus ==> doesn't match
any digits or string apple iphone 7s ==> doesn't match
Upvotes: 1
Reputation: 18135
With this regex you can match and also if you want can extract some info about it
(?!apple iphone .* plus)(?:apple iphone 7)(?>\s(?<storage>\d+)?\s?(?:gb))?
You can see the demo
I have updated a bit, now will match with the following
Will not match with the following
Upvotes: 0
Reputation: 16688
If you are really only interested in the Apple Iphone 7
bit of the string, and you're using PHP, why not simply do:
if (stripos($string,'Apple Iphone 7 Plus') !== FALSE) echo 'Wow a 7 Plus!';
else if (stripos($string,'Apple Iphone 7') !== FALSE) echo 'It is only a 7';
In other words: Avoid using complex regular expressions when you can, and only use them when they are needed.
Upvotes: 0