CachedRegexMatcher.cpp 2.1 KB

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