我正在撰寫相當于一個微型 DSL 的內容,其中每個腳本都是從單個字串中讀取的,如下所示:
"func1;func2;func1;4*func3;func1"
我需要擴展回圈,以便擴展的腳本是:
"func1;func2;func1;func3;func3;func3;func3;func1"
我使用帶有以下正則運算式的 C 標準正則運算式庫來查找這些回圈:
regex REGEX_SIMPLE_LOOP(":?[0-9] )\\*([_a-zA-Z][_a-zA-Z0-9]*;");
smatch match;
bool found = std::regex_search(*this, match, std::regex(REGEX_SIMPLE_LOOP));
現在,讀出回圈乘數并列印函式N次并不太難,但是我該如何用這個字串替換原來的匹配項呢?我想做這個:
if (found) match[0].replace(new_string);
但是我看不到圖書館可以做到這一點。
我的備份位置是regex_search,然后構建新字串,然后使用regex_replace,但它看起來笨拙且效率低下,并且基本上像這樣進行兩次完整搜索并不好。有沒有更清潔的方法?
uj5u.com熱心網友回復:
您也可以不使用正則運算式,決議并不太困難。所以正則運算式可能有點矯枉過正。此處演示:https ://onlinegdb.com/RXLqLtrUQ- (是的,我的輸出給出了額外的;最后)
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::istringstream is{ "func1;func2;func1;4*func3;func1" };
std::string split;
// use getline to split
while (std::getline(is, split, ';'))
{
// assume 1 repeat
std::size_t count = 1;
// if split part starts with a digit
if (std::isdigit(split.front()))
{
// look for a *
auto pos = split.find('*');
// the first part of the string contains the repeat count
auto count_str = split.substr(0, pos);
// convert that to a value
count = std::stoi(count_str);
// and keep the rest ("funcn")
split = split.substr(pos 1, split.size() - pos - 1);
}
// now use the repeat count to build the output string
for (std::size_t n = 0; n < count; n)
{
std::cout << split << ";";
}
}
// TODO invalid input string handling.
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/533373.html
標籤:C 正则表达式解析标记化
