//----------------------------------------------------------------------------- void mglParser::PutArg(std::wstring &str, bool def) { size_t pos = str.find('$',def?10:0); while(pos<str.length()) { wchar_t ch = str[pos+1]; if(ch>='0' && ch<='9') str.replace(pos,2,par[ch-'0']); else if(ch>='a' && ch<='z') str.replace(pos,2,par[ch-'a'+10]); else if(ch=='$') str.replace(pos,2,L"\uffff"); else str.replace(pos,1,L"\uffff"); pos = str.find('$',def?10:0); } while((pos = str.find(L'\uffff'))<str.length()) str[pos]='$'; }
/* ** Replaces %1, %2 etc with the corresponding measure value */ bool CMeter::ReplaceMeasures(const std::vector<std::wstring>& stringValues, std::wstring& str) { bool replaced = false; if (str.find(L'%') != std::wstring::npos) { WCHAR buffer[64]; // Create the actual text (i.e. replace %1, %2, .. with the measure texts) for (size_t i = stringValues.size(); i > 0; --i) { size_t len = _snwprintf_s(buffer, _TRUNCATE, L"%%%i", (int)i); size_t start = 0, pos; do { pos = str.find(buffer, start, len); if (pos != std::wstring::npos) { str.replace(pos, len, stringValues[i - 1]); start = pos + stringValues[i - 1].length(); replaced = true; } } while (pos != std::wstring::npos); } } return replaced; }
/* ** Replaces %1, %2, ... with the corresponding measure value. ** */ bool Meter::ReplaceMeasures(std::wstring& str, AUTOSCALE autoScale, double scale, int decimals, bool percentual) { bool replaced = false; if (str.find(L'%') != std::wstring::npos) { WCHAR buffer[64]; for (size_t i = m_Measures.size(); i > 0; --i) { size_t len = _snwprintf_s(buffer, _TRUNCATE, L"%%%i", (int)i); size_t start = 0, pos; const WCHAR* measureValue = m_Measures[i - 1]->GetStringOrFormattedValue( autoScale, scale, decimals, percentual); const size_t measureValueLen = wcslen(measureValue); do { pos = str.find(buffer, start, len); if (pos != std::wstring::npos) { str.replace(pos, len, measureValue, measureValueLen); start = pos + measureValueLen; replaced = true; } } while (pos != std::wstring::npos); } } return replaced; }
void ReplaceWString(std::wstring & str, const std::wstring & find, const std::wstring & replace) { for(auto i = str.find(find); i != std::wstring::npos ;i = str.find(find)) { str.replace(i, find.size(), replace); } }
std::wstring string_replace_all( std::wstring src, std::wstring const& target, std::wstring const& repl){ if (target.length() == 0) { // searching for a match to the empty string will result in // an infinite loop // it might make sense to throw an exception for this case return src; } if (src.length() == 0) { return src; // nothing to match against } size_t idx = 0; for (;;) { idx = src.find( target, idx); if (idx == std::wstring::npos) break; src.replace( idx, target.length(), repl); idx += repl.length(); } return src; }
void ReplaceString(std::wstring& input, const std::wstring placeholder, const std::wstring replacement) { size_t replaceStart = input.find(placeholder); if (replaceStart != std::string::npos) { input.replace(replaceStart, placeholder.length(), replacement); } }
static void ReplaceAll(std::wstring& str, const std::wstring& from, const std::wstring& to) { size_t start_pos = 0; while ((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); } }
static void replaceStringInPlace(std::wstring& subject, const std::wstring& search, const std::wstring& replace) { size_t pos = 0; while ((pos = subject.find(search, pos)) != std::wstring::npos) { subject.replace(pos, search.length(), replace); pos += replace.length(); } }
void StringUtil::replaceAll(std::wstring& src, const std::wstring& from, const std::wstring to) { size_t pos = 0; while((pos = src.find(from, pos)) != std::wstring::npos) { src.replace(pos, from.length(), to); pos += to.length(); } }
static void replace(std::wstring& s, std::wstring k, std::wstring r) { std::wstring::size_type p = 0; while ((p = s.find(k, p)) != std::wstring::npos) { s.replace(p, k.length(), r); p += r.length(); } }
void replaceAll(std::wstring& str, const std::wstring& from, const std::wstring& to) { if(from.empty()) return; size_t start_pos = 0; while((start_pos = str.find(from, start_pos)) != std::wstring::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx' } }
std::wstring ReplaceCharWithString(std::wstring source, const wchar_t replaceChar, std::wstring replaceString) { size_t posn = source.find(&replaceChar); while (posn != std::wstring::npos) { source.replace(posn, 1, replaceString); posn = source.find(&replaceChar, posn + replaceString.length()); } return source; }
void ReplaceStringInplace(std::wstring& str, const wchar_t* search, const wchar_t* replace) { size_t search_length = wcslen(search); size_t replace_length = wcslen(replace); size_t pos = 0; while ((pos = str.find(search, pos)) != std::wstring::npos) { str.replace(pos, search_length, replace); pos += replace_length; } }
void string_replace(std::wstring& strBig, const std::wstring & strsrc, const std::wstring &strdst) { std::wstring::size_type pos = 0; while ((pos = strBig.find(strsrc, pos)) != std::wstring::npos) { strBig.replace(pos, strsrc.length(), strdst); pos += strdst.length(); } }
void Mouse::ReplaceMouseVariables(std::wstring& result) const { // Check for new-style variables: [$MOUSEX] m_Skin->GetParser().ParseVariables(result, ConfigParser::VariableType::Mouse, m_Meter); // Check for old-style variables: $MOUSEX$ size_t start = 0, end; bool loop = true; do { start = result.find(L'$', start); if (start != std::wstring::npos) { size_t si = start + 1; end = result.find(L'$', si); if (end != std::wstring::npos) { size_t ei = end - 1; if (si != ei && result[si] == L'*' && result[ei] == L'*') { result.erase(ei, 1); result.erase(si, 1); start = ei; } else { std::wstring strVariable = result.substr(si, end - si); std::wstring value = m_Skin->GetParser().GetMouseVariable(strVariable, m_Meter); if (!value.empty()) { // Variable found, replace it with the value result.replace(start, end - start + 1, value); start += value.length(); } else { start = end; } } } else { loop = false; } } else { loop = false; } } while (loop); }
int install_util::ReplaceString(std::wstring& src_str, const std::wstring& old_str, const std::wstring& new_str) { int count = 0; std::wstring::size_type old_str_len = old_str.length(), new_str_len = new_str.length(); std::wstring::size_type pos = 0; while ((pos = src_str.find(old_str, pos)) != std::wstring::npos) { src_str.replace(pos, old_str_len, new_str); pos += new_str_len; ++count; } return count; }
static void clearCodeAssignments(std::wstring& s,const wchar_t* array,int count) { for (int i=0;i<count;i++) { std::wstring search(array); std::wstring r(L"DUMMY_ASSIGNMENT /*"); search += L"["; search += formatNumber(i); search += L"]"; r += search; search += L" = "; r += L"*/ = "; s.replace(s.find(search),search.size(),r); } }
void Replace(std::wstring& strText, const WCHAR * lpOldStr, const WCHAR * lpNewStr) { if (NULL == lpOldStr || NULL == lpNewStr) return; int nOldStrLen = wcslen(lpOldStr); int nNewStrLen = wcslen(lpNewStr); std::wstring::size_type nPos = 0; while ((nPos = strText.find(lpOldStr, nPos)) != std::wstring::npos) { strText.replace(nPos, nOldStrLen, lpNewStr); nPos += nNewStrLen; } }
std::wstring string_replace_first_instance( std::wstring src, std::wstring const& target, std::wstring const& repl){ // handle error situations/trivial cases if (target.length() == 0 || src.length() == 0) { return src; } size_t idx = 0; idx = src.find( target, idx); src.replace( idx, target.length(), repl); idx += repl.length(); return src; }
bool Cx_TextUtil::ReplaceAll(std::wstring& text, const std::wstring& match, const std::wstring& newtext) { long count = 0; size_t index = text.find(match); while (index != std::wstring::npos) { count++; text.replace(index, match.size(), newtext); index = text.find(match, index + newtext.size()); } return count > 0; }
int kbe_replace(std::wstring& str, const std::wstring& pattern, const std::wstring& newpat) { int count = 0; const size_t nsize = newpat.size(); const size_t psize = pattern.size(); for(size_t pos = str.find(pattern, 0); pos != std::wstring::npos; pos = str.find(pattern,pos + nsize)) { str.replace(pos, psize, newpat); count++; } return count; }
/* ** Substitues text using a straight find and replace method */ bool CMeasure::MakePlainSubstitute(std::wstring& str, size_t index) { size_t start = 0, pos; do { pos = str.find(m_Substitute[index], start); if (pos != std::wstring::npos) { str.replace(pos, m_Substitute[index].length(), m_Substitute[index + 1]); start = pos + m_Substitute[index + 1].length(); } } while (pos != std::wstring::npos); return true; }
void StringUtility::ReplaceAll( std::wstring& src,std::wstring oldValue,std::wstring newValue ) { size_t beginPos = 0; size_t findPos = -1; while(true) { findPos = src.find(oldValue,beginPos); if(findPos != std::wstring::npos) { src.replace(findPos,oldValue.length(),newValue); beginPos = findPos + newValue.length(); //Åųý¶ÔÔÀ´½øÐмì²â continue; } break; } }
int StringUtils::Replace(std::wstring &str, const std::wstring &oldStr, const std::wstring &newStr) { if (oldStr.empty()) return 0; int replacedChars = 0; size_t index = 0; while (index < str.size() && (index = str.find(oldStr, index)) != string::npos) { str.replace(index, oldStr.size(), newStr); index += newStr.size(); replacedChars++; } return replacedChars; }
/* ** Substitutes part of the text */ const WCHAR* Measure::CheckSubstitute(const WCHAR* buffer) { static std::wstring str; if (m_Substitute.empty()) { return buffer; } str = buffer; if (!m_RegExpSubstitute) { for (size_t i = 0, isize = m_Substitute.size(); i < isize; i += 2) { if (!m_Substitute[i].empty()) { MakePlainSubstitute(str, i); } else if (str.empty()) { // Empty result and empty substitute -> use second str = m_Substitute[i + 1]; } } } else { int ovector[300]; for (size_t i = 0, isize = m_Substitute.size(); i < isize; i += 2) { const char* error; int errorOffset; int offset = 0; pcre16* re = pcre16_compile( (PCRE_SPTR16)m_Substitute[i].c_str(), PCRE_UTF16, &error, &errorOffset, nullptr); // Use default character tables. if (!re) { MakePlainSubstitute(str, i); LogNoticeF(this, L"Substitute: %S", error); } else { do { const int options = str.empty() ? 0 : PCRE_NOTEMPTY; const int rc = pcre16_exec( re, nullptr, (PCRE_SPTR16)str.c_str(), (int)str.length(), offset, options, // Empty string is not a valid match ovector, (int)_countof(ovector)); if (rc <= 0) { break; } std::wstring result = m_Substitute[i + 1]; if (rc > 1) { for (int j = rc - 1 ; j >= 0 ; --j) { int newStart = ovector[2 * j]; size_t inLength = ovector[2 * j + 1] - ovector[2 * j]; if (newStart < 0) break; // Match was not found, so skip to the next item WCHAR tmpName[64]; size_t cutLength = _snwprintf_s(tmpName, _TRUNCATE, L"\\%i", j); size_t start = 0, pos; do { pos = result.find(tmpName, start, cutLength); if (pos != std::string::npos) { result.replace(pos, cutLength, str, (size_t)newStart, inLength); start = pos + inLength; } } while (pos != std::string::npos); } } const int start = ovector[0]; const int length = ovector[1] - ovector[0]; str.replace(start, length, result); offset = start + (int)result.length(); } while (true); pcre16_free(re); } } } return str.c_str(); }
/* ** GetFromWikia ** ** Download lyrics from LyricWiki. ** */ bool CLyrics::GetFromWikia(const std::wstring& artist, const std::wstring& title, std::wstring& data) { bool ret = false; std::wstring url = L"http://lyrics.wikia.com/api.php?func=getSong&fmt=json&artist=" + artist; url += L"&song="; url += title; data = CInternet::DownloadUrl(url, CP_UTF8); if (!data.empty()) { // First we get the URL to the actual wiki page std::wstring::size_type pos = data.find(L"http://"); if (pos != std::wstring::npos) { data.erase(0, pos); pos = data.find_first_of(L'\''); url.assign(data, 0, pos); // Fetch the wiki page data = CInternet::DownloadUrl(url, CP_UTF8); if (!data.empty()) { pos = data.find(L"'lyricbox'"); pos = data.find(L"&#", pos); if (pos != std::wstring::npos) { // Get and decode lyrics data.erase(0, pos); pos = data.find(L"<!"); data.resize(pos); CInternet::DecodeReferences(data); pos = data.find(L"[...]"); if (pos != std::wstring::npos) { // Skip incomplete lyrics return ret; } pos = data.find(L"<p>"); if (pos != std::wstring::npos) { // Skip unavailable lyrics return ret; } while ((pos = data.find(L"<br />"), pos) != std::wstring::npos) { data.replace(pos, 6, L"\n"); } // Get rid of all HTML tags std::wstring::size_type len = 0; while ((pos = data.find_first_of(L'<'), pos) != std::wstring::npos) { len = data.find_first_of(L'>', pos); len -= pos; data.erase(pos, ++len); } ret = true; } } } } return ret; }
void Decode(std::wstring& str, int opt) { // (opt <= 0 || opt > 3) : Do nothing. // (opt == 1) : Decode both numeric character references and character entity references. // (opt == 2) : Decode only numeric character references. // (opt == 3) : Decode only character entity references. if (opt >= 1 && opt <= 3) { std::wstring::size_type start = 0; while ((start = str.find(L'&', start)) != std::wstring::npos) { std::wstring::size_type end, pos; if ((end = str.find(L';', start)) == std::wstring::npos) break; pos = start + 1; if (pos == end) // &; - skip { start = end + 1; continue; } else if ((end - pos) > 10) // name (or number) is too long { ++start; continue; } if (str[pos] == L'#') // Numeric character reference { if (opt == 3 || // Decode only character entity references, ++pos == end) // &#; - skip { start = end + 1; continue; } int base; if (str[pos] == L'x' || str[pos] == L'X') { if (++pos == end) // &#x; or &#X; - skip { start = end + 1; continue; } base = 16; } else { base = 10; } std::wstring num(str, pos, end - pos); WCHAR* pch = nullptr; errno = 0; long ch = wcstol(num.c_str(), &pch, base); if (pch == nullptr || *pch != L'\0' || errno == ERANGE || ch <= 0 || ch >= 0xFFFE) // invalid character { start = pos; continue; } str.replace(start, end - start + 1, 1, (WCHAR)ch); ++start; } else // Character entity reference { if (opt == 2) // Decode only numeric character references - skip { start = end + 1; continue; } std::wstring name(str, pos, end - pos); WCHAR ch = GetEntityChar(name); if (ch) { str.replace(start, end - start + 1, 1, ch); } ++start; } } } }
/* ** Replaces measures in the given string. ** */ bool ConfigParser::ReplaceMeasures(std::wstring& result) { bool replaced = false; size_t start = 0; while ((start = result.find(L'[', start)) != std::wstring::npos) { size_t si = start + 1; size_t end = result.find(L']', si); if (end == std::wstring::npos) { break; } size_t next = result.find(L'[', si); if (next == std::wstring::npos || end < next) { size_t ei = end - 1; if (si != ei && result[si] == L'*' && result[ei] == L'*') { result.erase(ei, 1); result.erase(si, 1); start = ei; } else { std::wstring var = result.substr(si, end - si); Measure* measure = GetMeasure(var); if (measure) { const WCHAR* value = measure->GetStringOrFormattedValue(AUTOSCALE_OFF, 1, -1, false); size_t valueLen = wcslen(value); // Measure found, replace it with the value result.replace(start, end - start + 1, value, valueLen); start += valueLen; replaced = true; } else { std::wstring value; if (GetSectionVariable(var, value)) { // Replace section variable with the value. result.replace(start, end - start + 1, value); start += value.length(); replaced = true; } else { start = end; } } } } else { start = next; } } return replaced; }
/* ** Replaces environment and internal variables in the given string. ** */ bool ConfigParser::ReplaceVariables(std::wstring& result) { bool replaced = false; PathUtil::ExpandEnvironmentVariables(result); if (c_MonitorVariables.empty()) { SetMultiMonitorVariables(true); } // Check for variables (#VAR#) size_t start = 0, end; bool loop = true; do { start = result.find(L'#', start); if (start != std::wstring::npos) { size_t si = start + 1; end = result.find(L'#', si); if (end != std::wstring::npos) { size_t ei = end - 1; if (si != ei && result[si] == L'*' && result[ei] == L'*') { result.erase(ei, 1); result.erase(si, 1); start = ei; } else { std::wstring strVariable = result.substr(si, end - si); const std::wstring* value = GetVariable(strVariable); if (value) { // Variable found, replace it with the value result.replace(start, end - start + 1, *value); start += (*value).length(); replaced = true; } else { start = end; } } } else { loop = false; } } else { loop = false; } } while (loop); return replaced; }
//------------------------------------------------------------------------------------- bool Script::install(const wchar_t* pythonHomeDir, std::wstring pyPaths, const char* moduleName, COMPONENT_TYPE componentType) { std::wstring pySysPaths = SCRIPT_PATH; wchar_t* pwpySysResPath = strutil::char2wchar(const_cast<char*>(Resmgr::getSingleton().getPySysResPath().c_str())); strutil::kbe_replace(pySysPaths, L"../../res/", pwpySysResPath); pyPaths += pySysPaths; free(pwpySysResPath); #if KBE_PLATFORM == PLATFORM_WIN32 Py_SetPythonHome(const_cast<wchar_t*>(pythonHomeDir)); // 先设置python的环境变量 #else std::wstring fs = L";"; std::wstring rs = L":"; size_t pos = 0; while(true) { pos = pyPaths.find(fs, pos); if (pos == std::wstring::npos) break; pyPaths.replace(pos, fs.length(), rs); } Py_SetPath(pyPaths.c_str()); char* tmpchar = strutil::wchar2char(const_cast<wchar_t*>(pyPaths.c_str())); DEBUG_MSG(boost::format("Script::install: paths=%1%.\n") % tmpchar); free(tmpchar); #endif // Initialise python // Py_VerboseFlag = 2; Py_FrozenFlag = 1; // Warn if tab and spaces are mixed in indentation. // Py_TabcheckFlag = 1; Py_NoSiteFlag = 1; Py_IgnoreEnvironmentFlag = 1; Py_Initialize(); // python解释器的初始化 if (!Py_IsInitialized()) { ERROR_MSG("Script::install::Py_Initialize is failed!\n"); return false; } #if KBE_PLATFORM == PLATFORM_WIN32 PySys_SetPath(pyPaths.c_str()); #endif PyObject *m = PyImport_AddModule("__main__"); module_ = PyImport_AddModule(moduleName); // 添加一个脚本基础模块 if (module_ == NULL) return false; const char* componentName = COMPONENT_NAME_EX(componentType); if (PyModule_AddStringConstant(module_, "component", componentName)) { ERROR_MSG(boost::format("Script::init: Unable to set KBEngine.component to %1%\n") % componentName ); return false; } // 注册产生uuid方法到py APPEND_SCRIPT_MODULE_METHOD(module_, genUUID64, __py_genUUID64, METH_VARARGS, 0); if(!install_py_dlls()) { ERROR_MSG("Script::init: install_py_dlls() is failed!\n"); return false; } #ifndef KBE_SINGLE_THREADED s_pOurInitTimeModules = PyDict_Copy( PySys_GetObject( "modules" ) ); s_pMainThreadState = PyThreadState_Get(); s_defaultContext = s_pMainThreadState; PyEval_InitThreads(); KBEConcurrency::setMainThreadIdleFunctions( &Script::releaseLock, &Script::acquireLock ); #endif ScriptStdOutErr::installScript(NULL); // 安装py重定向模块 ScriptStdOutErrHook::installScript(NULL); static struct PyModuleDef moduleDesc = { PyModuleDef_HEAD_INIT, moduleName, "This module is created by KBEngine!", -1, NULL }; PyModule_Create(&moduleDesc); // 初始化基础模块 PyObject_SetAttrString(m, moduleName, module_); // 将模块对象加入main pyStdouterr_ = new ScriptStdOutErr(); // 重定向python输出 pyStdouterrHook_ = new ScriptStdOutErrHook(); if(!pyStdouterr_->install()){ // 安装py重定向脚本模块 ERROR_MSG("Script::install::pyStdouterr_->install() is failed!\n"); SCRIPT_ERROR_CHECK(); return false; } Pickler::initialize(); PyProfile::initialize(this); PyStruct::initialize(); Copy::initialize(); SCRIPT_ERROR_CHECK(); math::installModule("Math"); INFO_MSG("Script::install is successfully!\n"); return installExtraModule("KBExtra"); }