[英]How should you use C++11 Regex to create variables from a table stored in a text file?
這可能是一個相當瑣碎的問題,但是我對Regex在C ++中的工作方式感到困惑。 我有一個文本文件,如下所示:
Weapons: Cost Damage Armor
Dagger 8 4 0
Shortsword 10 5 0
Warhammer 25 6 0
Longsword 40 7 0
Greataxe 74 8 0
我想將每種武器的名稱,成本,傷害和裝甲存儲在結構中。 我嘗試使用以下代碼來做到這一點:
regex rule("(\\w+)\s(\\w+)\s(\\w+)\s(\\w+)");
smatch match;
for (int i = 0; i < 6; i++) {
if (regex_match(lines[i], match, rule)) {
struct Weapon Weapon;
Weapon.Name = match[1];
Weapon.Cost = stoi(match[2], NULL, 10);
Weapon.Damage = stoi(match[3], NULL, 10);
Weapon.ArmorValue = stoi(match[4], NULL, 10);
Weapons.push_back(Weapon);
}
}
但是,if語句始終返回false。
我使用正則表達式規則錯誤嗎?
我應該如何使用Regex將來自該表的數據存儲在結構中?
首先,我認為您的正則表達式應如下所示:
(\\\\ W +)\\\\ S +(\\\\ W +)\\\\ S +(\\\\ W +)\\\\ S +(\\\\ W +)
您只是在那里失去了空間。
現在,只需遍歷數組並記住第一個零匹配是“ Dagger 8 4 0”(帶空格)
編輯:下一場比賽將如下所示:
match [1] =“匕首”
match [2] =“ 8”
match [3] =“ 4”
match [4] =“ 0”
這是我的測試代碼:
std::string data = "Dagger 8 4 0";
std::regex rule("(\\w+)\\s+(\\w+)\\s+(\\w+)\\s+(\\w+)");
std::smatch match;
if (regex_match(data, match, rule)) {
std::cout << match[0] << std::endl << match[1] << match[2] << match[3] << match[4] << std::endl;
}
編輯2:我個人更願意使用\\ d而不是\\ w,這就是為什么:
假設其中一行如下所示:“ Dagger 3 3 word”
使用\\ w將使用'word'並且regex_match現在返回true,假設您的Weapon.ArmorValue是某種數值數據,此char *將被轉換為該數值,並且數據不會處於良好狀態。(*)
但是,使用\\ d會使您的regex_match返回false,因為'word'不是數字。 當然,我假設它們是整數(雙精度和浮點型將需要像\\ d +。\\ d +這樣的正則表達式),因此您的正則表達式現在看起來像這樣:
(\\ W +)\\ S +(\\ d +)\\ S +(\\ d +)\\ S +(\\ d +)
(*)甚至更糟-它可能會引發一些異常,這可能導致您的程序停止運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.