BehaviorTree
Core Library to create and execute Behavior Trees
Loading...
Searching...
No Matches
wildcards.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cstddef>
4#include <cstdint>
5#include <string_view>
6#include <vector>
7
8/**
9 * @file wildcards.hpp
10 * @brief Simple wildcard matching function supporting '*' and '?'.
11 *
12 * This file provides a function to match strings against patterns containing
13 * wildcard characters:
14 * - '*' matches any sequence of characters (including the empty sequence)
15 * - '?' matches any single character
16 *
17 * The implementation uses recursion with memoization to efficiently handle
18 * overlapping subproblems.
19 */
20
21inline bool wildcards_match(std::string_view str, std::string_view pattern)
22{
23 const size_t n = str.size();
24 const size_t m = pattern.size();
25
26 // Pre-allocate memo table: -1 = not computed, 0 = false, 1 = true
27 std::vector<int8_t> memo((n + 1) * (m + 1), -1);
28
29 auto get_memo = [&](size_t i, size_t j) -> int8_t& { return memo[i * (m + 1) + j]; };
30
31 auto match = [&](auto& match_ref, size_t i, size_t j) -> bool {
32 if(j == m)
33 {
34 return i == n;
35 }
36
37 int8_t& cached = get_memo(i, j);
38 if(cached != -1)
39 {
40 return cached == 1;
41 }
42
43 bool result = false;
44 if(pattern[j] == '*')
45 {
46 result = match_ref(match_ref, i, j + 1);
47 if(!result && i < n)
48 {
49 result = match_ref(match_ref, i + 1, j);
50 }
51 }
52 else if(i < n && (pattern[j] == '?' || pattern[j] == str[i]))
53 {
54 result = match_ref(match_ref, i + 1, j + 1);
55 }
56 else
57 {
58 result = false;
59 }
60
61 cached = result ? 1 : 0;
62 return result;
63 };
64
65 return match(match, 0, 0);
66}