CachedRegexMatcher.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //
  2. // Created by Tobias Hieta on 20/08/15.
  3. //
  4. #include "CachedRegexMatcher.h"
  5. #include "QsLog.h"
  6. /////////////////////////////////////////////////////////////////////////////////////////
  7. bool CachedRegexMatcher::addMatcher(const QString& pattern, const QVariant& result)
  8. {
  9. QRegExp matcher(pattern);
  10. if (!matcher.isValid())
  11. {
  12. QLOG_WARN() << "Could not compile pattern:" << pattern;
  13. return false;
  14. }
  15. m_matcherList.push_back(qMakePair(matcher, result));
  16. return true;
  17. }
  18. /////////////////////////////////////////////////////////////////////////////////////////
  19. QVariantList CachedRegexMatcher::match(const QString& input)
  20. {
  21. // first we check if this match has already happened before
  22. if (m_matcherCache.contains(input))
  23. return m_matcherCache.value(input);
  24. QVariantList matches;
  25. // otherwise try to iterate our list and find a match
  26. for(const MatcherValuePair& matcher : m_matcherList)
  27. {
  28. QRegExp re(matcher.first);
  29. if (re.indexIn(input) != -1)
  30. {
  31. // found match
  32. QVariant returnValue = matcher.second;
  33. if (re.captureCount() > 0 && matcher.second.type() == QVariant::String)
  34. {
  35. QString value(matcher.second.toString());
  36. for (int i = 0; i < re.captureCount(); i ++)
  37. {
  38. QString argFmt = QString("%%1").arg(i + 1);
  39. if (value.contains(argFmt))
  40. value = value.arg(re.cap(i + 1));
  41. }
  42. returnValue = QVariant(value);
  43. }
  44. matches << returnValue;
  45. }
  46. }
  47. QLOG_DEBUG() << "No match for:" << input;
  48. if (!matches.isEmpty())
  49. {
  50. m_matcherCache.insert(input, matches);
  51. return matches;
  52. }
  53. return QVariantList();
  54. }
  55. /////////////////////////////////////////////////////////////////////////////////////////
  56. void CachedRegexMatcher::clear()
  57. {
  58. m_matcherCache.clear();
  59. m_matcherList.clear();
  60. }