[英]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. 我的前缀是
download-
我的后缀是-free
,我需要一个正则表达式来捕获的话google-chrome
,如果输入的字符串没有download-
和-free
的前缀和后缀,拍摄的组是字符串本身。
String 1 = download-google-chrome-free (with prefix and sufix) 字符串1 = download-google-chrome-free(带前缀和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) 字符串2 =谷歌浏览器(无前缀和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
使用PHP
。
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
. 如果字符串中没有前缀或后缀,则这些捕获组在
$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. 现在
$match[1]
将包含您想要的浏览器名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.