I'm writing some code for the Arduino and wanted to parse some settings that will be inputted. The settings must be DIGITS1 = DIGITS2, DIGITS3 = DIGITS4 etc - like the following
2 = 202,1 = 103, 9 = 202
Spaces don't matter and there can be multiple identities (separated by a comma) or only one. At the moment, I'm just looking to see whether its valid
Is there an easy way to do this on the Arduino? Would regex help here (assuming there is a library for it on Arduino?
I've written the below which seems to work following some tests but its long and ugly!
bool checkSettings (String settingStr)
{
if (settingStr.length() == 0) //settings cannot be empty
returnfalse;
for (int i = 0; i < settingStr.length(); i++) //this deals with the whole string
{
bool firstNum = false, secondNum = false, equalsSign = false; //these mark whether each sentence has required characters
for (int j = i; j < settingStr.length(); j++) //this deals with each sentence
{
if (firstNum && secondNum && equalsSign) //for this sentence we have found all required elements
{
if (settingStr[j] != ',' && j != settingStr.length() - 1) //should end with a comma or be the end of the whole string otherwise fail
returnfalse;
else //finished with this sentence move to next
{
i = j;
break;
}
}
if (!firstNum) //expecting first number
{
if (settingStr[j] == ' ')
continue;
if (!isDigit(settingStr[j])) //return false as must be a digit
returnfalse;
for (int k = j + 1; j < settingStr.length(); k++) //see what trails the first digit
{
if (!isDigit(settingStr[k])) //not a digit so stop looking
{
firstNum = true; //found our number
j = k; //set j back to our non-digit index
break;
}
}
}
if (firstNum && !equalsSign ) //expecting equals sign
{
if (settingStr[j] == ' ')
continue;
if (settingStr[j] != '=')
returnfalse;
else
{
j = j + 1;
equalsSign = true;
}
}
if (firstNum && equalsSign && !secondNum) //expecting third number
{
if (settingStr[j] == ' ')
continue;
if (!isDigit(settingStr[j])) //return false as must be a digit
returnfalse;
for (int l = j + 1; l < settingStr.length(); l++)
{
if (!isDigit(settingStr[l]) || l == settingStr.length() - 1) //if next character not a digit or end of whole sentence then go to exit procedure above
{
secondNum = true;
j = l - 1;
break;
}
}
}
}
}
returntrue;
}
I am not sure what is available on the Arduino.
Normally you can use a stringstream and getline to split your string into substrings with ',' as separator.
For each string you can use the find method of the string to locate the '=' and use the substring function get the key and value. Finally you convert the value to an int.
OR
You could use a second stringstream and use >> to extract the key, '=', and value.