2011-03-20 104 views
1

我再次尋求更多關於心意的知識。C++正則表達式多行替換

我有一個C++解決方案,它使用Boost庫,因爲解決方案需要在Linux環境中工作。然而,我的知識是在C#中,C++是我潛入的一個有點新的領域。

我正在尋找如何創建一個有點模板並通過正則表達式替換值的示例使用?

這裏就是我談論的例子:

<VirtualHost *:80> 
    ServerName {$1}.somedomain.com 
    ServerAlias {$1} 
    ServerAdmin [email protected] 

    <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. 

理想情況下,一個函數/方法將能夠處理這個,所以我可以通過說一個存儲庫對象,然後通過它來呈現它。

非常感謝, 肖恩

+0

這是幾乎不是很像XML風格的模板您的想法或要求?因爲...這是一個可怕的想法。 – Tomalak 2011-03-20 11:58:53

+1

你好Tomalak,不幸的是它是一個要求。我並不是瘋狂地想出這樣瘋狂的東西呢。以上是使用svn的啓用mod的apache的VirtualHost。歡呼聲,Shaun – shauny 2011-03-20 12:06:44

回答

1

其實,你不需要正則表達式的能力,你可以用做查找/替換。

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應該是包含與換行符整個模板大的字符串。

+0

工程魅力,代碼奇妙peice。歡呼聲Vlad :) – shauny 2011-03-20 12:39:46

+0

@shauny:不客氣! – Vlad 2011-03-20 12:42:15