Это старый поток, но он все еще находится в верхней части результатов поиска, поэтому я добавляю свое решение, используя std :: stringstream и простой метод замены строки Yves Baumes, который я нашел здесь.
Следующий пример будет читать файл по строкам, игнорировать строки комментариев, начинающиеся с //, и анализировать другие строки в комбинации строк, ints и double. Stringstream выполняет разбор, но ожидает, что поля будут разделены пробелами, поэтому я использую stringreplace, чтобы сначала включить запятые в пространства.
Плохой или отсутствующий ввод просто игнорируется, что может быть или не быть хорошим, в зависимости от ваших обстоятельств.
#include <string>
#include <sstream>
#include <fstream>
void StringReplace(std::string& str, const std::string& oldStr, const std::string& newStr)
// code by Yves Baumes
// http://stackoverflow.com/questions/1494399/how-do-i-search-find-and-replace-in-a-standard-string
{
size_t pos = 0;
while((pos = str.find(oldStr, pos)) != std::string::npos)
{
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
void LoadCSV(std::string &filename) {
std::ifstream stream(filename);
std::string in_line;
std::string Field;
std::string Chan;
int ChanType;
double Scale;
int Import;
while (std::getline(stream, in_line)) {
StringReplace(in_line, ",", " ");
std::stringstream line(in_line);
line >> Field >> Chan >> ChanType >> Scale >> Import;
if (Field.substr(0,2)!="//") {
// do your stuff
// this is CBuilder code for demonstration, sorry
ShowMessage((String)Field.c_str() + "\n" + Chan.c_str() + "\n" + IntToStr(ChanType) + "\n" +FloatToStr(Scale) + "\n" +IntToStr(Import));
}
}
}
Кто-нибудь знает лучший способ определения / разграничения представления или запроса, написанного в Legacy или Standard SQL, с использованием API BigQuery?
blockquote>Вы можете попробовать использовать регулярное выражение javascript определить тип SQL.
Вы можете использовать приведенный ниже фрагмент кода в качестве базовой линии
isStandardSql(idString) { let isStandard, fullId, partialId, projectId = ''; // This 'if' checks if the provided idString is of type standard and makes sure there is only one ':' in the expression (as in legacy syntax) const splitted = idString.split(/[:.]/g); if (splitted.length > 3) { const __ret = this.try2findProjectId(idString, projectId); idString = __ret.idString; projectId = __ret.projectId; } if ((idString.match(/:/g))) { // Regex that checks if the format of the id match legacy let matched = idString.match(/([\[]([^[]|[\[][\]])*[\]])/g); if (matched && matched[0]) { fullId = projectId + matched[0].substring(1, idString.length - 1); isStandard = false; } else { this.errorMessage("First Regex", idString); } // Same as the first only that here instead of ':' we are looking for '.' and we want to make sure there is more than 1 (as in standard syntax) } else if ((idString.match(/\./g) && idString.match(/\./g).length === 2)) { // Regex that checks if the format of the id match standard let matched = idString.match(/(`([^`]|``)*`)/g);// ? idString.match(/(`([^`]|``)*`)/g) : [idString]; if (matched && matched[0]) { fullId = projectId + matched[0].substring(1, idString.length - 1); isStandard = true } else if(!matched && idString){ fullId = projectId + idString; isStandard = true; } else { this.errorMessage("Second Regex", idString); } } else {//projectID.dataset // In case of id without projectId of proxy "use" project.dataset if(splitted.length === 2) { fullId = ''; if (idString[0] === '[' && idString[idString.length - 1] === ']') { isStandard = false; } else if (idString[0] === '`' && idString[idString.length - 1] === '`') { isStandard = true; } partialId = idString.replace(/`|\[|\]/g, '') } else { this.errorMessage("Third Regex", idString); } } // Return values is flag the determine the type (standard or legacy) and id without staring/ ending chars (``, []) return { isStandard, fullId: fullId, partialId: partialId }; } try2findProjectId(idString, projectId) { let numOfInstances = 0 for (let i = idString.length; i > 0; i--) { const char = idString[i - 1] if (char === ':' || char === '.') { numOfInstances++ if (numOfInstances === 2) { projectId = idString.substring(1, i - 1) idString = idString.substring(i - 1, idString.length) idString = idString[idString.length - 1] === '`' ? '`' + idString : idString idString = idString[idString.length - 1] === ']' ? '[' + idString : idString } } } return {idString, projectId} }