1 /* 2 * Copyright (C) 2022 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 17 #pragma once 18 19 #include <memory> 20 #include <optional> 21 #include <string> 22 #include <string_view> 23 #include <vector> 24 25 namespace simpleperf { 26 27 class RegExMatch { 28 public: 29 virtual ~RegExMatch(); 30 virtual bool IsValid() const = 0; 31 virtual std::string GetField(size_t index) const = 0; 32 virtual void MoveToNextMatch() = 0; 33 }; 34 35 // A wrapper of std::regex, converting std::regex_error exception into return value. 36 class RegEx { 37 public: 38 static std::unique_ptr<RegEx> Create(std::string_view pattern); ~RegEx()39 virtual ~RegEx() {} GetPattern()40 const std::string& GetPattern() const { return pattern_; } 41 42 virtual bool Match(std::string_view s) const = 0; 43 virtual bool Search(std::string_view s) const = 0; 44 // Always return a not-null RegExMatch. If no match, RegExMatch->IsValid() is false. 45 virtual std::unique_ptr<RegExMatch> SearchAll(std::string_view s) const = 0; 46 virtual std::optional<std::string> Replace(const std::string& s, 47 const std::string& format) const = 0; 48 49 protected: RegEx(std::string_view pattern)50 RegEx(std::string_view pattern) : pattern_(pattern) {} 51 52 std::string pattern_; 53 }; 54 55 bool SearchInRegs(std::string_view s, const std::vector<std::unique_ptr<RegEx>>& regs); 56 57 } // namespace simpleperf 58