使用C++ regex实现文本正则替换

Posted by VK on July 29, 2019

1. 使用C++ regex实现文本正则替换

用法参考

1.1意义

原始TextID如下:

> <LangIDID=”LANG.GLOBAL_WIZARD_WLAN_SEARCH_VIEW.Info.text” Text=”Pleasesearch for %1 on your mobile device.\nNetwork key:%2”/>

遇到这种含有%1, %2的TextID时,可以用C++11 regex_replace将占位符替换成目标文本,这样就不用写死在自己的代码里面,方便与项目更新的TextID同步。

1.2 修改方法

原代码:

void SVPWizardWLANDlg::updateText()
{
	uint32_t langId = -1;
	SVP_GetLanguage(langId);
	std::string str1 = (langId == LID_EN_US) ? "Please search for " : "请通过您的移动电话查找\n";
	std::string str2 = (langId == LID_EN_US) ? "\non your mobile device.\nNetwork key:" : "\n网络密钥:";
	std::string str = str1 + m_APSSID + str2 + m_APPassword;
	LauncherApplication::m_data.WizardWLANSearchInfo = str.c_str();
}

更改后的代码:

#include <regex>

void SVPWizardWLANDlg::updateText()
{
	std::string str = SVPSingleton<TranslateData>::getInstance()->
        GetDataString(LANG_GLOBAL_WIZARD_WLAN_SEARCH_VIEW_Info_text);
    const std::regex e1("(%1)"), e2("(%2)");
    str = std::regex_replace(str, e1, m_APSSID);
    str = std::regex_replace(str, e2, m_APPassword);
	LauncherApplication::m_data.WizardWLANSearchInfo = str.c_str();
}