regex - 仅匹配以字符开头的

标签 regex

我有这个正则表达式来匹配 HTML 代码中的图像 URL:

$regex = '#[\w,=/:.-]+\.(?:jpe?g|png|gif)#iu';

Regex demo

Php demo :

$input = <<<HTML
<a href="https://e...content-available-to-author-only...e.com/example1.jpg">
<a href="https://e...content-available-to-author-only...e.com/ストスト.jpg">
<a href="https://e...content-available-to-author-only...e.com/example3.jpg">
<a href="https://e...content-available-to-author-only...e.com/example3.bak">
HTML;

$dom = new DomDocument();
$dom->loadHTML(mb_convert_encoding($input, 'HTML-ENTITIES', "UTF-8"));

$anchors = $dom->getElementsByTagName("a");
$regex = '#^[\w,=/:.-]+\.(?:jpe?g|png|gif)$#iu';

foreach ($anchors as $anchor) {
    $res = $anchor->getAttribute("href");
    if (preg_match($regex, $res)) {
        echo "Valid url: $res" . PHP_EOL;
    } else {
        echo "Invalid url: $res" . PHP_EOL;
    }
}

我的问题是,如何让它只匹配以 http// 开头的。目前它与 example.jpg 匹配,它不是完整的 URL。

最佳答案

我建议这样的模式:href="((?:http|\/\/)[^"]+\.(?:jpe?g|png|gif))"

解释:

href=" - 从字面上匹配 href=",它将确保您匹配超链接

(...) - 捕获组以存储实际链接

(?:...) - 非捕获组

http|\/\/ - 匹配 http//

[^"]+ - 匹配 "

以外的任何字符中的 1+ 个

\. - 按字面匹配 .

jpe?g|png|gif - 改变,匹配选项 jpegjpg 中的一个(由于 e? ), png, gif

" - 按字面匹配 "

Demo

匹配的链接将在第一个捕获组内。

关于regex - 仅匹配以字符开头的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60452074/

相关文章:

python - 使用 re 和 base64 模块对字符串的一部分进行 Base64 解码

javascript - 正则表达式只允许文本框中的一个点

java - 为什么java正则表达式replaceAll()只返回最后一个匹配项

javascript - 正则表达式和 JavaScript 字符串末尾带有美元 ($)

Python 正则表达式 : How to specify an optional match (for potentially empty sub expression)?

python - 与模式匹配且不包含某些单词的字符串

javascript - 使用正则表达式去除空格

python - 用于查找文件路径的正则表达式

javascript - 正则表达式匹配具有确切标识符字符数的字符串

python - 为什么此 RegEx 找不到任何数据?