/// <summary> /// Parses the given search query from its raw representation. /// </summary> /// <param name="query">Raw query.</param> /// <returns>Search query.</returns> public static SearchQuery Parse(string query) { Match m = null; Criterion c = null; SearchQuery ret = null; string currentQuery = query; if (!string.IsNullOrEmpty(currentQuery)) { ret = new SearchQuery(); while((m = Regex.Match(currentQuery, "([a-zA-Z0-9]+):((\"[^\"]+\")|([^\\s]+))", RegexOptions.IgnoreCase)).Success) { c = new Criterion(); c.Name = m.Groups[1].Value; c.Value = (m.Groups[2].Value ?? string.Empty).Trim().Trim('\"'); if(!string.IsNullOrEmpty(c.Value)) ret.Criteria.Add(c); currentQuery = currentQuery.Remove(m.Index, m.Length); } currentQuery = currentQuery.Trim(); if (!string.IsNullOrEmpty(currentQuery)) ret.Criteria.Add(new Criterion(string.Empty, currentQuery)); } return ret; }
/// <summary> /// Removes criterion with the given name. /// </summary> /// <param name="name">Criterion name.</param> /// <returns>New search query.</returns> public SearchQuery WithoutCriterion(string name) { int index = -1; SearchQuery ret = new SearchQuery(Criteria); if (name != null && ret.Criteria != null) { for (int i = 0; i < ret.Criteria.Count; i++) { if (ret.Criteria[i] != null && string.Compare(ret.Criteria[i].Name ?? string.Empty, name, System.StringComparison.InvariantCultureIgnoreCase) == 0) { index = i; break; } } if (index >= 0) ret.Criteria.RemoveAt(index); } return ret; }
/// <summary> /// Adds or updates criterion with the given name. /// </summary> /// <param name="name">Criterion name.</param> /// <param name="value">Criterion value.</param> /// <returns>New search query.</returns> public SearchQuery WithCriterion(string name, string value) { int index = -1; SearchQuery ret = new SearchQuery(Criteria); if (name != null && !string.IsNullOrEmpty(value)) { if (ret.Criteria == null) ret.Criteria = new List<Criterion>(); for (int i = 0; i < ret.Criteria.Count; i++) { if (ret.Criteria[i] != null && string.Compare(ret.Criteria[i].Name ?? string.Empty, name, System.StringComparison.InvariantCultureIgnoreCase) == 0) { index = i; break; } } if (index < 0) ret.Criteria.Add(new Criterion(name, value)); else ret.Criteria[index].Value = value; } return ret; }