[英]Splitting a string with regex, ignoring delimiters that occur within braces
假設我有一個字符串
Max and Bob and Merry and {Jack and Co.} and Lisa
。
我需要將其拆分and
作為分隔符, 但前提是它不會出現在花括號中 。
所以從上面的字符串我應該得到5個字符串:
Max
, Bob
, Merry
, Jack and Co.
, Lisa
。
我試過這樣的模式:
[^\\\{.+]\\band\\b[^.+\\\}]
但它不起作用 - Jack
和Co.
仍然分裂(我使用C ++所以我必須兩次逃避特殊字符)。
這是一個可能的解決方案,部分基於bobble-bubble的評論。 它將根據請求生成五個字符串,不包含空格或大括號。
std::string text = "Max and Bob and Merry and {Jack and Co.} and Lisa";
std::regex re(R"(\}? +and +(?![^{]*\})\{?)");
std::sregex_token_iterator it(text.begin(), text.end(), re, -1);
std::sregex_token_iterator end;
while (it != end)
std::cout << *it++ << std::endl;
我試圖保持簡單,你可能想要替換周圍的空間and
完整的空白檢測。 此處提供交互式版本。
讓{...}
部分先匹配。 也就是說,把它放在|
的左側 。
\{.*?\}|and
如果可能,那將匹配{foo and bar}
,但如果沒有,那么它將嘗試匹配and
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.