我想编写一个动态搜索函数,它读取一个字符串并将其拆分取决于一些常量。
我的示例代码仅适用于搜索字符串,而不适用于它的不同变体。
// String to clean
searchString = "month == Jan || (name == “ni*” && age > 18)";
const string ageStr = "age";
const string monthStr = "month == ";
const string nameStr = "name == ";
const string startQutation = "“";
const string endQutation = "”";
const string star = "*";
string month = searchString.Substring(searchString.IndexOf(monthStr) + 9, 3);
searchString = searchString.Remove(searchString.IndexOf(monthStr), 12);
string nameOrginal = searchString.Substring(searchString.IndexOf(startQutation) + 1,
searchString.IndexOf(endQutation) - searchString.IndexOf("“") - 1);
string name = nameOrginal;
if (name.Contains("*"))
{
name = name.Remove(name.IndexOf(star), 1);
}
searchString = searchString.Remove(searchString.IndexOf(nameStr), 8 + nameOrginal.Length + 2);
string ageCompare = searchString.Substring(searchString.IndexOf(ageStr) + 6, 2);
ageCompare = ageCompare.Trim();
string age = searchString.Substring(searchString.IndexOf(ageStr) + 8, 2);
MessageBox.Show(string.Format("Name: {0}\nMonth: {1}\nAge:{2}\nAge compare operator:{3}",
name, month, age, ageCompare));
结果是并且应该是:month = "jan" name = "ni" age = 18 ageCompare = ">"
我需要一个更好的函数来清除常量之后的字符串,这样如果字符串与硬编码字符串不同,它就不会出错。
此致