简体   繁体   中英

Regex negative prefix and suffix

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM