C++正则表达式多行替换

标签 c++ regex boost

我再次寻求更多关于心灵的知识。

我有一个使用 Boost 库的 C++ 解决方案,因为该解决方案需要在 Linux 环境中工作。但是,我的知识在 C# 内,而 C++ 是我涉足的一个新领域。

我正在寻找一个示例,说明如何创建某种模板并通过正则表达式替换值?

这是我正在谈论的例子:

<VirtualHost *:80>
    ServerName  {$1}.somedomain.com
    ServerAlias {$1}
    ServerAdmin mr.admin@somedomain.com

    <Location />
        DAV svn
        SVNPath /some/dir/{$2}/{$3}/{$4}
        AuthType Basic
        AuthName "{$5}"
        AuthUserFile /some/dir/{$2}/{$3}/{$4}/{$4}.users
        Require valid-user
    </Location>
</VirtualHost>

以及值的键: { 已经格式化,只需要用 $n 替换即可 }

$1 = sub domain alias (3 characters long)
$2 = is either "public" or "private"
$3 = a users username (no more than 25 characters)
$4 = the svn project name (no more than 30 characters and " " replaced with "_")
$5 = the actual repository name given by the user.

理想情况下,一个函数/方法将能够处理这个,这样我就可以传递一个存储库对象,然后通过它呈现它。

非常感谢, 肖恩

最佳答案

实际上,您不需要正则表达式的强大功能,您可以使用查找/替换。

void replaceall(string& source, const string& pattern, const string& replacement)
{
    int curr = 0;
    while ((curr = str.find(pattern, curr)) != string::npos)
        str.replace(curr, parrern.length(), replacement);
}

void substitutetemplate(
        const string& subDomainAlias,
        bool publicOrPrivate,
        const string& userName,
        const string& svnProjectName,
        const string& repositoryName)
{
    string result = m_template;

    replaceall(result, "{$1}", subDomainAlias);

    string pop = publicOrPrivate ? "public" : "private";
    replaceall(result, "{$2}", pop);

    replaceall(result, "{$3}", userName);

    string svnProjectNameWithoutSpaces = svnProjectName;
    replaceall(svnProjectNameWithoutSpaces, " ", "_");
    replaceall(result, "{$4}", svnProjectNameWithoutSpaces);

    replaceall(result, "{$5}", repositoryName);
    m_result = result;
}

m_template 应该是一个大字符串,包含带有换行符的整个模板。

关于C++正则表达式多行替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5368300/

相关文章:

c++ - 尝试用 codelite/g++ 编译

c++ - libjit 什么时候真正值得?

C++ fstream写入文件非常慢

regex - 是否可以改进此正则表达式以在 Excel 单元格中查找编号的文本行以避免错误匹配?

java - 使用正则表达式从操作数中拆分并提取运算符

c++ - 'boost::Q_FOREACH' 尚未声明

c++ - "Functionoids"?

c++ - C++ 中的函数组合

c++ - 计算数组行中的总和

php - 用单个空格替换制表符和空格,用单个换行符替换回车和换行符