gpt4 book ai didi

php - PHP`preg_match_all` 函数的 Boost::regexp 模拟是什么?

转载 作者:行者123 更新时间:2023-11-30 04:33:35 24 4
gpt4 key购买 nike

所以我有这样的 php 函数,我想翻译成 C++:

protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName)
{
preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1);
preg_match_all("#<{$tag}[^>]*$valueName=['\"](.+?)['\"][^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*/?>#i", $content, $matches2);

$result = array_merge($matches1[1], $matches2[1]);
return empty($result)?false:$result[0];
}

使用示例:

            $location = $this->htmlTag($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content');
$server = $this->htmlTag($content, 'link', 'rel', 'openid.server', 'href');
$delegate = $this->htmlTag($content, 'link', 'rel', 'openid.delegate', 'href');

(内容是 $content= curl_exec($curl); 的结果)

preg_match_all - 在主题中搜索与模式中给定的正则表达式的所有匹配项,并按照标志指定的顺序将它们放入匹配项中。找到第一个匹配后,后续搜索从最后一个匹配结束继续。

如何使用 boost::regexp 翻译它?

最佳答案

像这样:

boost::optional<std::string> htmlTag(const std::string& content,
const std::string& tag, const std::string& attrName,
const std::string& attrValue, const std::string& valueName)
{
const std::string
expr1 = boost::format("#<%1[^>]*%2=['\"].*?%3.*?['\"][^>]"
"*%4=['\"](.+?)['\"][^>]*/?>#i")
% tag % attrName % attrValue % valueName,
expr2 = boost::format("#<%1[^>]*%2=['\"](.+?)['\"][^>]*"
"%3=['\"].*?%4.*?['\"][^>]*/?>#i")
% tag % attrName % attrValue % valueName;

boost::match_results<std::string::const_iterator>
matches1, matches2, result;

// do the searches (note: these probably need to be loops as shown at the bottom of this page:
// http://www.boost.org/doc/libs/1_47_0/libs/regex/doc/html/boost_regex/ref/regex_search.html
if (!regex_search(content, matches1, expr1))
return boost::none;
if (!regex_search(content, matches2, expr2))
return boost::none;

result = // merge matches1[1] and matches2[1] somehow
if (result.empty())
return boost::none;
else
return result[0];
}

我确定我弄错了一些细节(一方面,我认为你需要根据评论一遍又一遍地调用 regex_search),但希望你能解决这些细节并发布你完成的解决方案。

关于php - PHP`preg_match_all` 函数的 Boost::regexp 模拟是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6725035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com