1 // =================================
 2 // Copyright (c) 2024 Seppo Laakko
 3 // Distributed under the MIT license
 4 // =================================
 5 
 6 using System;
 7 using System.Collections;
 8 
 9 namespace System.RegularExpressions
10 {
11     public ustring MakeRegularExpressionPatternFromFilePattern(const ustring& filePattern)
12     {
13         ustring pattern;
14         for (uchar c : filePattern)
15         {
16             switch (c)
17             {
18                 case '.':
19                 {
20                     pattern.Append(u"\\.");
21                     break;
22                 }
23                 case '*':
24                 {
25                     pattern.Append(u".*");
26                     break;
27                 }
28                 case '?':
29                 {
30                     pattern.Append(u".");
31                     break;
32                 }
33                 default:
34                 {
35                     pattern.Append(c1);
36                     break;
37                 }
38             }
39         }
40         return pattern;
41     }
42 
43     [nodiscard]
44     public Result<bool> FilePatternMatch(const ustring& filePathconst ustring& filePattern)
45     {
46         return PatternMatch(filePathMakeRegularExpressionPatternFromFilePattern(filePattern));
47     }
48 
49     [nodiscard]
50     public Result<bool> PatternMatch(const ustring& strconst ustring& regularExpressionPattern)
51     {
52         Context context;
53         Result<Nfa> nfa = CompileRegularExpressionPattern(contextregularExpressionPattern);
54         if (nfa.Error())
55         {
56             return Result<bool>(ErrorId(nfa.GetErrorId()));
57         }
58         return Result<bool>(PatternMatch(strnfa.Value()));
59     }
60 
61     [nodiscard]
62     public Result<Nfa> CompileRegularExpressionPattern(Context& contextconst ustring& regularExpressionPattern)
63     {
64         int count = context.GetNextRegExCount();
65         System.RegularExpressions.RegExLexer lexer(regularExpressionPattern.Chars()regularExpressionPattern.Chars() + regularExpressionPattern.Length()
66             "regular_expression_" + ToString(count));
67         System.Lex.XmlParsingLog log(Console.Error());
68         if (System.RegularExpressions.DebugParsing())
69         {
70             lexer.SetLog(&log);
71         }
72         return System.RegularExpressions.RegExParser<System.RegularExpressions.RegExLexer>.Parse(lexer&context);
73     }
74 
75     [nodiscard]
76     public Result<Nfa> CompileFilePattern(Context& contextconst ustring& filePattern)
77     {
78         return CompileRegularExpressionPattern(contextMakeRegularExpressionPatternFromFilePattern(filePattern));
79     }
80 
81     public bool PatternMatch(const ustring& strNfa& nfa)
82     {
83         return Match(nfastr);
84     }
85