如何创建Regex以返回最后一个连字符之后的所有内容



我正在尝试创建regex(我一直在努力解决的问题(,以返回最后一个连字符之后的所有内容。

例如,这些将是输入字符串:https://mywebsite.com/company/company-name-page-ddd.lhttps://mywebsite.com/company/another-company-page-lloy.l

我只想返回ddd.l,或者在第二个例子中返回lloy.l

我认为它应该是^-([a-zA-Z0-9-.=^$]+(/?$但这并不能解决URL和目录的第一部分。

这必须是纯regex,因此没有php作为用户端wordpress插件中的过滤器。

有人能帮忙吗?

您可以绕过锚点,以$结束,而不是以^开始

然后您必须从字符类中删除-。该值在组1中。

-([a-zA-Z0-9.=^$]+)$

Regex演示

如果支持,您也可以匹配连字符并使用K,或者使用正向查找在左侧(?<=-)上断言连字符并省略组以获得仅匹配的

-K[a-zA-Z0-9.=^$]+$(?<=-)[a-zA-Z0-9.=^$]+$

如前所述,php被标记为:

$strings = [
"https://mywebsite.com/company/company-name-page-ddd.l",
"https://mywebsite.com/company/another-company-page-lloy.l"
];
foreach ($strings as $s) {
preg_match("~-K[a-zA-Z0-9.=^$]+$~", $s, $match);
echo $match[0] . PHP_EOL;
}

输出

ddd.l
lloy.l

我会在这里使用preg_replace来去除从输入开始到最后一个破折号(包括(的所有内容:

$input = "Some text here - and other text as well - the end";
$output = preg_replace("/^.*-/", "", $input);
echo $input . "n" . $output;

此打印:

Some text here - and other text as well - the end
the end

我认为你的问题是,你用^-开始了这个表达式,但它不匹配。

如果我读了你的问题描述,我想你希望整行都是完全匹配的,但只希望匹配组中最后一个连字符之后的部分。为了做到这一点,我建议从^.*开始,以便在一开始就抓住一切。

所以完整的正则表达式是:

^.*-([w.]+)$

我真的很推荐unsinghttps://regex101.com/开发regex。

php > preg_match('/^.*-([w.]+)$/', "https://mywebsite.com/company/company-name- 
page-ddd.l" , $matches);
php > print_r($matches);
Array
(
[0] => https://mywebsite.com/company/company-name-page-ddd.l
[1] => ddd.l
)

^.*(-.*)$

说明:断言行首,然后选择任意字符0次或多次,然后(并开始捕获(连字符,然后再选择任意字符零次或多次(并结束捕获(,然后断言行尾。

第一个捕获组将拥有您需要的内容。

最新更新