Regex.cpp (2480B)
1 // Copyright (c) Microsoft Corporation. 2 // Licensed under the MIT License. 3 #include "pch.h" 4 #include "TestCommon.h" 5 #include <winget/Regex.h> 6 #include <AppInstallerStrings.h> 7 8 using namespace std::string_view_literals; 9 using namespace AppInstaller::Regex; 10 11 12 TEST_CASE("Regex_Construction", "[regex]") 13 { 14 Expression empty; 15 REQUIRE(!empty); 16 17 Expression lowerVowels("(a|e|i|o|u)"); 18 REQUIRE(lowerVowels); 19 20 // Ensure functionality to later verify against copy 21 REQUIRE(lowerVowels.IsMatch(L"a")); 22 REQUIRE(!lowerVowels.IsMatch(L"b")); 23 24 Expression copy = lowerVowels; 25 REQUIRE(copy); 26 27 // Ensure that the copy can also work 28 REQUIRE(lowerVowels.IsMatch(L"a")); 29 REQUIRE(copy.IsMatch(L"a")); 30 31 REQUIRE(!lowerVowels.IsMatch(L"b")); 32 REQUIRE(!copy.IsMatch(L"b")); 33 34 Expression moved = std::move(copy); 35 REQUIRE(moved); 36 37 REQUIRE(moved.IsMatch(L"a")); 38 REQUIRE(!moved.IsMatch(L"b")); 39 } 40 41 TEST_CASE("Regex_IsMatch", "[regex]") 42 { 43 Expression ArchitectureX32{ R"((X32|X86)(?=\P{Nd}|$)(?:\sEDITION)?)", Options::CaseInsensitive }; 44 45 REQUIRE(ArchitectureX32.IsMatch(L"X32")); 46 REQUIRE(ArchitectureX32.IsMatch(L"X86 edition")); 47 48 REQUIRE(!ArchitectureX32.IsMatch(L"Not a match")); 49 REQUIRE(!ArchitectureX32.IsMatch(L"X86 editions")); 50 } 51 52 TEST_CASE("Regex_Replace", "[regex]") 53 { 54 Expression test{ R"((b|d\s|vy))" }; 55 REQUIRE(test.Replace(L"The bright and swervy", {}) == std::wstring{ L"The right answer" }); 56 57 Expression vowels{ "(a|e|i|o|u)", Options::CaseInsensitive }; 58 REQUIRE(vowels.Replace(L"The QUICK brown fox jumped over the lazy dog.", L"[$0]") == std::wstring{ L"Th[e] Q[U][I]CK br[o]wn f[o]x j[u]mp[e]d [o]v[e]r th[e] l[a]zy d[o]g." }); 59 } 60 61 TEST_CASE("Regex_ForEach", "[regex]") 62 { 63 std::wstring input = L"The words in the Sentence but no more"; 64 std::vector<std::wstring> expected = { L"The", L"words", L"in", L"the", L"Sentence" }; 65 66 Expression test{ R"(\S+)" }; 67 68 size_t i = 0; 69 test.ForEach(input, 70 [&](bool isMatch, std::wstring_view text) 71 { 72 if (!isMatch) 73 { 74 REQUIRE(text == L" "); 75 return true; 76 } 77 else 78 { 79 REQUIRE(i < expected.size()); 80 REQUIRE(text == expected[i]); 81 ++i; 82 83 return i < expected.size(); 84 } 85 }); 86 }