Reputation: 934
I have these strings for example:
download-google-chrome-free
download-mozilla-firefox-free
And also these strings:
google-chrome
mozilla-firefox
My prefix is download-
and my suffix is -free
, I need a regular expression to capture the words google-chrome
, If the input string does not have download-
and -free
prefix and suffix, the group captured is the string itself.
String 1 = download-google-chrome-free (with prefix and sufix)
String 1 Group 1 = download-
String 1 Group 2 = google-chrome
String 1 Group 3 = -free
String 2 = google-chrome (without prefix and sufix)
String 2 Group 1 = '' (empty)
String 2 Group 2 = google-chrome (empty)
String 2 Group 3 = '' (empty)
You can do that? I am using PHP
using preg_match
.
Upvotes: 0
Views: 1020
Reputation: 781058
preg_match('/(download-)?(google-chrome|mozilla-firefox)(-free)?/', $string, $match);
The ?
indicates that the group before it is optional. If the prefix or suffix isn't in the string, those capture groups will be empty in $match
.
If you don't actually want to return the groups with the optional prefix and suffix, make them non-capturing groups by putting ?:
at the beginning of the group:
preg_match('/(?:download-)?(google-chrome|mozilla-firefox)(?:-free)?/', $string, $match);
Now $match[1]
will contain the browser name that you want.
Upvotes: 1