Monday, January 28, 2013

Convert an SQL like pattern into a regular expression pattern

  1. var pattern = Regex.Replace(
  2. likePattern,
  3. @"[%_]|\[[^]]*\]|[^%_[]+",
  4. match =>
  5. {
  6. if (match.Value == "%")
  7. {
  8. return ".*";
  9. }
  10. if (match.Value == "_")
  11. {
  12. return ".";
  13. }
  14. if (match.Value.StartsWith("[") && match.Value.EndsWith("]"))
  15. {
  16. return match.Value;
  17. }
  18. return Regex.Escape(match.Value);
  19. });

No comments: