簡體   English   中英

C#正則表達式到C ++ boost :: regex

[英]C# Regex to C++ boost::regex

我需要匹配以下形式的C ++代碼中的字符串

L, N{1, 3}, N{1, 3}, N{1, 3} 

其中在上述偽代碼中, L始終是字母(大寫或小寫) 句號( .字符),而N始終是數字[0-9]

這樣明確地,我們可能有B, 999, 999, 999., 8, 8, 8但數字字符的數量總是每個之后的相同,並且是1,2或3個數字長度; 所以D, 23, 232, 23不可能的。

在C#中,我將按以下方式進行匹配

string s = "   B,801, 801, 801 other stuff";
Regex reg = new Regex(@"[\.\w],\s*\d{1,3},\s*\d{1,3},\s*\d{1,3}");
Match m = reg.Match(s);

大。 但是,我需要使用boost::regex類似的正boost::regex 我嘗試過

std::string s = "   B,801, 801, 801 other stuff";
boost::regex regex("[\\.\w],\s*\d{1,3},\s*\d{1,3},\s*\d{1,3}");
boost::match_results<std::string::const_iterator> results;
boost::regex_match(s, results, regex);

但這給了我'w' : unrecognized character escape sequence ,與sd相同。 但是從文檔的印象中,我可以毫無問題地使用\\d\\s\\w

我在這里做錯了什么?


編輯。 根據上面的評論,我已經切換到std::regex 現在,大概是正則表達式是相同的,以下代碼可以編譯,但是正則表達式不 匹配...

std::string p = "XX";
std::string s = "    B,801, 801, 801 other stuff";
std::regex regex(R"del([\.\w],\s*\d{1,3},\s*\d{1,3},\s*\d{1,3})del");
if (std::regex_match(s, regex))
   p = std::regex_replace(s, regex, "");

您可以在正則表達式中使用\\w\\s\\d 但是,這不是您在做什么; 您正在嘗試使用\\w作為字符串中的字符。 為了使實際字符串中有一個\\后跟w ,您需要轉義\\ (當然,與sd相同):

boost::regex regex("[\\.\\w],\\s*\\d{1,3},\\s*\\d{1,3},\\s*\\d{1,3}");

從C ++ 11開始,您可以使用原始字符串文字使您的代碼與C#版本更加相似:

boost::regex regex(R"del([\.\w],\s*\d{1,3},\s*\d{1,3},\s*\d{1,3})del");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM