Regex.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * Copyright (C) 2018 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "Regex.h"
  17. namespace android {
  18. namespace vintf {
  19. namespace details {
  20. Regex::~Regex() {
  21. clear();
  22. }
  23. void Regex::clear() {
  24. if (mImpl != nullptr) {
  25. regfree(mImpl.get());
  26. mImpl = nullptr;
  27. }
  28. }
  29. bool Regex::compile(const std::string& pattern) {
  30. clear();
  31. mImpl = std::make_unique<regex_t>();
  32. int status = regcomp(mImpl.get(), pattern.c_str(), REG_EXTENDED | REG_NEWLINE);
  33. return status == 0;
  34. }
  35. bool Regex::matches(const std::string& s) const {
  36. regmatch_t match;
  37. int status =
  38. regexec(mImpl.get(), s.c_str(), 1 /* nmatch */, &match /* pmatch */, 0 /* flags */);
  39. return status == 0 && match.rm_so == 0 && match.rm_eo >= 0 &&
  40. static_cast<size_t>(match.rm_eo) == s.length();
  41. }
  42. } // namespace details
  43. } // namespace vintf
  44. } // namespace android