2016-04-29 39 views
2

這是我有,但它不起作用時,嘗試匹配,我不知道爲什麼。我的正則表達式爲xml標記不起作用

this is a start tag: " <House>" 
this is a end tag: " </House>" 
This is a data tag: " <City>Allentown</City>" 

而且要匹配的字符串是XML文件的一列(因此它在一開始的縮進空格),因爲我通過線去行。

我用正則表達式和其他服務,它看起來像它使用正則表達式STL

這是不工作

if (regex_match(line, starttag)) 
{ 
    cout << "Start tag" << endl; 
} 
if (regex_match(line, endtag)) 
{ 
    cout << "End tag" << endl; 
} 
if (regex_match(line, taganddata)) 
{ 
    cout << "Data and Tags" << endl; 
} 
+1

提示:' 「\ S * <\w*>」'是包含字母s,該符號的字符串,小於號,字母w,星號和大於號。它不包含任何反斜槓。它也應該生成一個編譯器警告。 – immibis

+0

但是\ w不代表任何單詞字符? – fman

+0

但是你的字符串不包含\ w,它包含了w。 – immibis

回答

2

你的正則表達式需要轉義匹配存在,但不是在我的C++程序正常。即正斜槓必須正確轉義

regex starttag("(.*)<\\w*>"); 
regex endtag("(.*)<\\/\\w*>"); 
regex taganddata(".*<\\w*>\\w*<\\/\\w*>"); 

或者,你可以使用Raw string format:

regex starttag(R"((.*)<\w*>)"); 
regex endtag(R"((.*)<\/\w*>)"); 
regex taganddata(R"(.*<\w*>\w*<\/\w*>)"); 
+0

哇,我不知道是什麼。謝謝 – fman