### Configure and Install RE2 Pkgconfig File Source: https://github.com/google/re2/blob/main/CMakeLists.txt Configures and installs the RE2 pkgconfig file. ```cmake configure_file(${CMAKE_CURRENT_SOURCE_DIR}/re2.pc.in ${CMAKE_CURRENT_BINARY_DIR}/re2.pc @ONLY) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/re2.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) ``` -------------------------------- ### Install Bazelisk Source: https://github.com/google/re2/blob/main/README.md Install Bazelisk, a tool to manage Bazel versions, using go install or Homebrew on macOS. ```bash go install github.com/bazelbuild/bazelisk@latest # or on mac: brew install bazelisk ``` -------------------------------- ### Build RE2 with Make Source: https://github.com/google/re2/blob/main/README.md Basic installation and testing of RE2 using GNU make. Ensure C++17 compiler and Abseil library are available. ```bash make make test make benchmark make install make testinstall ``` -------------------------------- ### Install RE2 Library and Headers Source: https://github.com/google/re2/blob/main/CMakeLists.txt Installs the RE2 library, headers, and related files. ```cmake install(TARGETS re2 EXPORT re2Targets ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} FRAMEWORK DESTINATION ${CMAKE_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/re2 INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(EXPORT re2Targets DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/re2 NAMESPACE re2::) ``` -------------------------------- ### Build and Test with Bazel Source: https://github.com/google/re2/blob/main/README.md Build and test the project using Bazel after installing Bazelisk. Ensure C++17 compatibility. ```bash bazelisk build :all bazelisk test :all ``` -------------------------------- ### Python RE2 Module API Examples Source: https://context7.com/google/re2/llms.txt Provides a comprehensive overview of the `google-re2` Python module, showcasing basic matching, compilation, findall, finditer, substitution, splitting, and advanced features like options, sets, and filters. ```python import re2 # Basic matching assert re2.fullmatch(r'h.*o', 'hello') assert re2.search(r'\d+', 'abc123def').group() == '123' assert re2.match(r'\w+', 'hello world').group() == 'hello' # Compile for reuse pattern = re2.compile(r'(\w+):(\d+)') match = pattern.fullmatch('host:8080') print(match.group(0)) # 'host:8080' print(match.group(1)) # 'host' print(match.group(2)) # '8080' print(match.groups()) # ('host', '8080') # Find all matches text = 'apple:1 banana:2 cherry:3' matches = pattern.findall(text) # [('apple', '1'), ('banana', '2'), ('cherry', '3')] # Iterator for large texts for m in pattern.finditer(text): print(f'{m.group(1)} = {m.group(2)}') # Substitution result = re2.sub(r'(\w+)', r'[\1]', 'hello world') # '[hello] [world]' result, count = re2.subn(r'\d', 'X', 'a1b2c3') # ('aXbXcX', 3) # Split parts = re2.split(r'\s+', 'one two three') # ['one', 'two', 'three'] # Options opts = re2.Options() opts.case_sensitive = False pattern = re2.compile(r'hello', options=opts) assert pattern.fullmatch('HELLO') # Set for multiple pattern matching s = re2.Set.SearchSet() s.Add(r'\d+') s.Add(r'[a-z]+') s.Compile() matches = s.Match('abc123') # Returns [0, 1] # Filter for prefiltered matching f = re2.Filter() f.Add(r'hello.*world') f.Add(r'foo\d+bar') f.Compile() matches = f.Match('hello beautiful world') ``` -------------------------------- ### Configure RE2 Package Configuration Files Source: https://github.com/google/re2/blob/main/CMakeLists.txt Configures and installs the RE2 package configuration files for CMake. ```cmake configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/re2Config.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/re2Config.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/re2) write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/re2ConfigVersion.cmake VERSION ${SONAME}.0.0 COMPATIBILITY SameMajorVersion) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/re2Config.cmake ${CMAKE_CURRENT_BINARY_DIR}/re2ConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/re2) ``` -------------------------------- ### C++ Named Capturing Groups Example Source: https://context7.com/google/re2/llms.txt Demonstrates using named capturing groups in RE2 C++ for extracting submatches by name. Shows how to access group names and indices, and extract values using `PartialMatch`. ```cpp #include #include #include #include int main() { RE2 re("(?Phttps?)://(?P[^/:]+)(?::(?P\d+))?(?P/.*)?"); // Check number of capturing groups std::cout << "Groups: " << re.NumberOfCapturingGroups() << std::endl; // Get name-to-index mapping const std::map& named = re.NamedCapturingGroups(); for (const auto& [name, index] : named) { std::cout << " " << name << " -> " << index << std::endl; } // Output: // host -> 2 // path -> 4 // port -> 3 // protocol -> 1 // Get index-to-name mapping const std::map& indexed = re.CapturingGroupNames(); for (const auto& [index, name] : indexed) { std::cout << " " << index << " -> " << name << std::endl; } // Extract by position (named groups work like regular groups) std::string protocol, host, port, path; RE2::PartialMatch( "https://api.example.com:8080/v1/users", re, &protocol, &host, &port, &path); std::cout << "Protocol: " << protocol << std::endl; // https std::cout << "Host: " << host << std::endl; // api.example.com std::cout << "Port: " << port << std::endl; // 8080 std::cout << "Path: " << path << std::endl; // /v1/users return 0; } ``` -------------------------------- ### Build RE2 with CMake (No Tests/Benchmarks) Source: https://github.com/google/re2/blob/main/README.md Build RE2 using CMake without tests or benchmarks, which avoids the need for GoogleTest and Benchmark dependencies. ```bash rm -rf build cmake -S . -B build cd build make make install ``` -------------------------------- ### Create RE2 Benchmark Executable Source: https://github.com/google/re2/blob/main/CMakeLists.txt Creates an executable for a RE2 benchmark and links necessary libraries. ```cmake add_executable(${target} re2/testing/${target}.cc) if(BUILD_SHARED_LIBS AND WIN32) target_compile_definitions(${target} PRIVATE -DRE2_CONSUME_TESTING_DLL) endif() target_compile_features(${target} PUBLIC ${RE2_CXX_VERSION}) target_link_libraries(${target} PUBLIC testing re2 benchmark::benchmark_main ${EXTRA_TARGET_LINK_LIBRARIES}) ``` -------------------------------- ### Add and Commit Changes Source: https://github.com/google/re2/wiki/Contribute Stage changes in a specific file and then commit them. This is the standard way to record changes before creating a commit message. ```bash $ git add re2/re2.cc $ git commit ``` -------------------------------- ### Configure Git URL Source: https://github.com/google/re2/wiki/Contribute Verify that your Git repository is cloned from GitHub. If not, this command shows the current remote origin URL. ```bash $ git config remote.origin.url ``` -------------------------------- ### Define Benchmark Executable Targets Source: https://github.com/google/re2/blob/main/CMakeLists.txt Lists the executables to be built for benchmarking RE2. ```cmake set(BENCHMARK_TARGETS regexp_benchmark ) ``` -------------------------------- ### FilteredRE2 - Add and Compile Patterns Source: https://context7.com/google/re2/llms.txt Demonstrates adding multiple regex patterns to FilteredRE2 and compiling them to extract filter strings for preliminary matching. ```cpp #include #include #include #include #include int main() { FilteredRE2 f; int id; // Add patterns f.Add("hello.*world", RE2::DefaultOptions, &id); // id = 0 f.Add("foo\d+bar", RE2::DefaultOptions, &id); // id = 1 f.Add("test\w+case", RE2::DefaultOptions, &id); // id = 2 // Compile and get filter strings std::vector strings_to_match; f.Compile(&strings_to_match); // strings_to_match now contains literal substrings like: // "hello", "world", "foo", "bar", "test", "case" // These can be searched using fast string matching (Aho-Corasick, etc.) std::cout << "Filter strings:" << std::endl; for (size_t i = 0; i < strings_to_match.size(); i++) { std::cout << " " << i << ": " << strings_to_match[i] << std::endl; } // Simulate string matching results (indices of matched filter strings) // In real use, this would come from a fast string matcher std::vector atoms = {0, 1}; // Found "hello" (0) and "world" (1) // Find first matching regexp int match = f.FirstMatch("hello beautiful world", atoms); // match == 0 (pattern "hello.*world") // Find all matching regexps std::vector matching_regexps; f.AllMatches("hello beautiful world", atoms, &matching_regexps); // Get potential matches (may have false positives) std::vector potentials; f.AllPotentials(atoms, &potentials); // Access individual RE2 objects const RE2& re = f.GetRE2(0); std::cout << "Pattern 0: " << re.pattern() << std::endl; return 0; } ``` -------------------------------- ### Build RE2 with CMake Source: https://github.com/google/re2/blob/main/README.md Build RE2 using CMake, enabling tests and benchmarks. This method can help if the standard Makefile has issues finding dependencies. ```bash rm -rf build cmake -DRE2_TEST=ON -DRE2_BENCHMARK=ON -S . -B build cd build make make test make install ``` -------------------------------- ### Find Benchmark Package Source: https://github.com/google/re2/blob/main/CMakeLists.txt Finds the benchmark package if it's not already found. ```cmake if(NOT TARGET benchmark::benchmark) find_package(benchmark REQUIRED) endif() ``` -------------------------------- ### Configure RE2 Framework Build on Apple Source: https://github.com/google/re2/blob/main/CMakeLists.txt Enables framework building for RE2 on macOS if RE2_BUILD_FRAMEWORK is set. ```cmake if(APPLE AND RE2_BUILD_FRAMEWORK) set_target_properties(re2 PROPERTIES FRAMEWORK TRUE FRAMEWORK_VERSION A MACOSX_FRAMEWORK_IDENTIFIER com.googlesource.code.re2) endif() ``` -------------------------------- ### RE2 Matching Interface Source: https://github.com/google/re2/blob/main/README.md Demonstrates the basic matching operations provided by the RE2 C++ API, including FullMatch and PartialMatch. ```APIDOC ## RE2 Matching Interface ### Description This section covers the fundamental matching functions in the RE2 C++ API: `RE2::FullMatch` and `RE2::PartialMatch`. - `RE2::FullMatch`: Requires the regular expression to match the entire input text. - `RE2::PartialMatch`: Searches for a match of a substring within the input text, returning the leftmost-longest match (or Perl-equivalent in Perl mode). ### Method C++ Functions ### Endpoint N/A (C++ Library) ### Request Example ```cpp // FullMatch example assert(RE2::FullMatch("hello", "h.*o")); assert(!RE2::FullMatch("hello", "e")); // PartialMatch example assert(RE2::PartialMatch("hello", "h.*o")); assert(RE2::PartialMatch("hello", "e")); ``` ### Response #### Success Response (Boolean) - `true`: Indicates a successful match. - `false`: Indicates no match found. #### Response Example (Boolean return values as shown in the request examples) ``` -------------------------------- ### Create RE2 Test Executable Source: https://github.com/google/re2/blob/main/CMakeLists.txt Creates an executable for a specific RE2 test case and links necessary libraries. ```cmake add_executable(${target} re2/testing/${target}.cc) if(BUILD_SHARED_LIBS AND WIN32) target_compile_definitions(${target} PRIVATE -DRE2_CONSUME_TESTING_DLL) endif() target_compile_features(${target} PUBLIC ${RE2_CXX_VERSION}) target_link_libraries(${target} PUBLIC re2 testing GTest::gtest_main ${EXTRA_TARGET_LINK_LIBRARIES}) add_test(NAME ${target} COMMAND ${target}) ``` -------------------------------- ### Configure Testing Library for DLL on Windows Source: https://github.com/google/re2/blob/main/CMakeLists.txt Sets a compile definition for the testing library when building shared libraries on Windows. ```cmake if(BUILD_SHARED_LIBS AND WIN32) target_compile_definitions(testing PRIVATE -DRE2_BUILD_TESTING_DLL) endif() ``` -------------------------------- ### Configure Regex Behavior with RE2::Options Source: https://context7.com/google/re2/llms.txt Customize RE2's matching behavior using RE2::Options. Options include case sensitivity, dot matching newline, memory limits, longest match preference, and literal matching. ```cpp #include #include #include int main() { // Quiet mode - suppress error logging for invalid patterns RE2 re1("(invalid", RE2::Quiet); if (!re1.ok()) { std::cerr << "Error: " << re1.error() << std::endl; } // Latin-1 encoding instead of UTF-8 RE2 re2("caf\xe9", RE2::Latin1); // Matches Latin-1 "café" // POSIX mode - leftmost-longest matching RE2 re3("a+", RE2::POSIX); // Custom options RE2::Options opts; opts.set_case_sensitive(false); // Case-insensitive matching opts.set_dot_nl(true); // Dot matches newline opts.set_max_mem(1 << 20); // Limit to 1MB memory opts.set_longest_match(true); // Prefer longest match RE2 re4("hello.*world", opts); assert(RE2::PartialMatch("HELLO\nWORLD", re4)); // Works due to options // Never match newline RE2::Options strict_opts; strict_opts.set_never_nl(true); RE2 re5(".*", strict_opts); // Newlines won't be matched even with . // Literal mode - pattern treated as literal string RE2::Options literal_opts; literal_opts.set_literal(true); RE2 re6("a.b", literal_opts); assert(RE2::FullMatch("a.b", re6)); // Matches literal "a.b" assert(!RE2::FullMatch("aXb", re6)); // Does NOT match "aXb" return 0; } ``` -------------------------------- ### Define Test Executable Targets Source: https://github.com/google/re2/blob/main/CMakeLists.txt Lists the executables to be built for testing RE2. ```cmake set(TEST_TARGETS charclass_test compile_test filtered_re2_test mimics_pcre_test parse_test possible_match_test re2_test re2_arg_test regexp_test required_prefix_test search_test set_test simplify_test string_generator_test dfa_test exhaustive1_test exhaustive2_test exhaustive3_test exhaustive_test random_test ) ``` -------------------------------- ### Configure Git User Name and Email Source: https://github.com/google/re2/wiki/Contribute Set the default user name and email address for Git commits. This is necessary if these configurations are not already set globally. ```bash $ git config user.name "Grace R. Emlin" $ git config user.email gre@swtch.com ``` -------------------------------- ### Fetch and Rebase Remote Changes Source: https://github.com/google/re2/wiki/Contribute Update your local repository with the latest changes from the remote repository and rebase your local commits on top of them. This helps synchronize your work with the main branch. ```bash $ git fetch origin $ git rebase origin/main ``` -------------------------------- ### C++ LazyRE2 for Thread-Safe Global Patterns Source: https://context7.com/google/re2/llms.txt Illustrates the use of `LazyRE2` for thread-safe initialization of global RE2 patterns in C++. This avoids static initialization order issues and ensures safe concurrent access to patterns. ```cpp #include #include #include #include // Global patterns using LazyRE2 (thread-safe, initialized on first use) static LazyRE2 kEmailPattern = {"[\\w.]+@[\\w.]+"}; static LazyRE2 kPhonePattern = {"\\d{3}-\\d{3}-\\d{4}"}; static LazyRE2 kUrlPattern = {"https?://[\\w./]+"}; // With options static LazyRE2 kCaseInsensitive = {"hello", RE2::Latin1}; bool ValidateEmail(const std::string& email) { return RE2::FullMatch(email, *kEmailPattern); } bool ValidatePhone(const std::string& phone) { return RE2::FullMatch(phone, *kPhonePattern); } std::string ExtractUrl(const std::string& text) { std::string url; if (RE2::PartialMatch(text, *kUrlPattern, &url)) { return url; } return ""; } int main() { // Safe to use from multiple threads std::vector threads; for (int i = 0; i < 10; i++) { threads.emplace_back([i]() { std::string email = "user" + std::to_string(i) + "@example.com"; bool valid = ValidateEmail(email); // All threads safely share the same RE2 object }); } for (auto& t : threads) { t.join(); } // Access pattern properties std::cout << "Email pattern: " << kEmailPattern->pattern() << std::endl; std::cout << "Groups: " << kEmailPattern->NumberOfCapturingGroups() << std::endl; return 0; } ``` -------------------------------- ### Link Testing Library Source: https://github.com/google/re2/blob/main/CMakeLists.txt Links the testing library against RE2 and GTest. ```cmake target_link_libraries(testing PUBLIC re2 GTest::gtest) ``` -------------------------------- ### Run RE2 Tests Source: https://github.com/google/re2/wiki/Contribute Execute all tests for the RE2 project to ensure changes do not introduce regressions. This command should be run before submitting code for review. ```bash $ cd your_re2_root $ make test ``` -------------------------------- ### Link RE2 to Threads on UNIX Source: https://github.com/google/re2/blob/main/CMakeLists.txt Links the RE2 library to the Threads library on UNIX-like systems. ```cmake if(UNIX) target_link_libraries(re2 PUBLIC Threads::Threads) endif() ``` -------------------------------- ### RE2::Consume - Incremental Text Scanning in C++ Source: https://context7.com/google/re2/llms.txt Utilize RE2::Consume for incremental parsing and tokenization of text. It matches patterns at the beginning of a string_view and advances the view past the matched text, useful for processing structured data streams. ```cpp #include #include #include #include int main() { // Parse key-value pairs std::string contents = "name = 42\ncount = 100\nmax = 999\n"; absl::string_view input(contents); std::string var; int value; while (RE2::Consume(&input, "(\w+) = (\d+)\n", &var, &value)) { std::cout << var << " -> " << value << std::endl; } // Output: // name -> 42 // count -> 100 // max -> 999 // Tokenize CSV-like data std::string csv = "apple,banana,cherry,date"; absl::string_view csv_view(csv); std::string token; // First token (no comma prefix) if (RE2::Consume(&csv_view, "([^,]+)", &token)) { std::cout << "Token: " << token << std::endl; // apple } // Remaining tokens while (RE2::Consume(&csv_view, ",([^,]+)", &token)) { std::cout << "Token: " << token << std::endl; // banana, cherry, date } return 0; } ``` -------------------------------- ### Perl-compatible Magic Constructs Source: https://github.com/google/re2/blob/main/doc/syntax.html These constructs allow for arbitrary Perl code execution or advanced grouping and recursion within the regex. ```regex (?{code}) ``` ```regex (??{code}) ``` ```regex (?n) ``` ```regex (?+n) ``` ```regex (?-n) ``` ```regex (?C) ``` ```regex (?R) ``` ```regex (?&name) ``` ```regex (?P=name) ``` ```regex (?P>name) ``` ```regex (?(cond)true|false) ``` ```regex (?(cond)true) ``` -------------------------------- ### RE2::Match - Low-Level Matching with Position Control Source: https://context7.com/google/re2/llms.txt Utilizes RE2::Match for flexible matching, allowing control over search position, anchoring, and submatch extraction. Useful for complex scenarios. ```cpp #include #include #include #include int main() { RE2 re("(\w+):(\d+)"); absl::string_view text = "prefix host:8080 suffix"; // Submatch array: [0] = full match, [1] = first group, etc. absl::string_view submatch[3]; // Match with position control bool matched = re.Match( text, 7, // startpos - begin search here 16, // endpos - stop search here RE2::UNANCHORED, // anchor type submatch, // output array 3 // number of submatches to extract ); if (matched) { std::cout << "Full match: " << submatch[0] << std::endl; // "host:8080" std::cout << "Group 1: " << submatch[1] << std::endl; // "host" std::cout << "Group 2: " << submatch[2] << std::endl; // "8080" } // Different anchor modes RE2 pattern("\d+"); absl::string_view num_text = "42abc"; absl::string_view result[1]; // ANCHOR_START - must match at beginning pattern.Match(num_text, 0, num_text.size(), RE2::ANCHOR_START, result, 1); // result[0] == "42" // ANCHOR_BOTH - must match entire string (like FullMatch) bool full = pattern.Match(num_text, 0, num_text.size(), RE2::ANCHOR_BOTH, result, 1); // full == false (doesn't match entire string) // Fast existence check (nsubmatch = 0) bool exists = re.Match(text, 0, text.size(), RE2::UNANCHORED, nullptr, 0); return 0; } ``` -------------------------------- ### RE2 Pre-Compiled Regular Expressions Source: https://github.com/google/re2/blob/main/README.md Explains how to pre-compile a regular expression into an RE2 object for efficient reuse. ```APIDOC ## RE2 Pre-Compiled Regular Expressions ### Description To avoid recompiling the same regular expression multiple times, you can compile it once into an `RE2` object and then reuse this object for subsequent matching operations. This is more efficient for repeated use of a pattern. ### Method C++ Class and Functions ### Endpoint N/A (C++ Library) ### Parameters #### Constructor - `RE2(const string& re)`: Constructor that takes the regular expression pattern string. #### Member Functions - `ok()`: Returns `true` if the regular expression was compiled successfully, `false` otherwise. Use `error()` to get the error message if compilation failed. ### Request Example ```cpp // Compile the regex once RE2 re("(\w+):(\d+)"); assert(re.ok()); // Check if compilation was successful // Reuse the compiled regex for matching string s; int i; assert(RE2::FullMatch("ruby:1234", re, &s, &i)); assert(RE2::FullMatch("ruby:1234", re, &s)); assert(RE2::FullMatch("ruby:1234", re, (void*)NULL, &i)); assert(!RE2::FullMatch("ruby:123456789123", re, &s, &i)); ``` ### Response #### Success Response (Boolean) - `true`: Indicates a successful match using the pre-compiled regex. - `false`: Indicates no match or failure. #### Response Example (Boolean return values as shown in the request examples) ``` -------------------------------- ### Link RE2 to ABSL Dependencies Source: https://github.com/google/re2/blob/main/CMakeLists.txt Links the RE2 library to ABSL dependencies, working around a CMake issue. ```cmake foreach(dep ${ABSL_DEPS}) # Work around https://gitlab.kitware.com/cmake/cmake/-/issues/16899. >:( string(PREPEND dep "^") string(REGEX REPLACE "\^absl_" "absl::" dep ${dep}) target_link_libraries(re2 PUBLIC ${dep}) endforeach() ``` -------------------------------- ### Repetition Operators Source: https://github.com/google/re2/wiki/Syntax Use *, +, and ? for zero or more, one or more, and zero or one repetitions, respectively. Parentheses can group expressions. ```regex e1* ``` ```regex e1+ ``` ```regex e1? ``` ```regex (ab*) ``` -------------------------------- ### Unicode Character Classes Source: https://github.com/google/re2/wiki/Syntax Match Unicode character properties using \p and \P, with or without one-letter names. ```regex \pN ``` ```regex \p{Greek} ``` ```regex \PN ``` ```regex \P{Greek} ``` -------------------------------- ### Define Testing Sources for RE2 Source: https://github.com/google/re2/blob/main/CMakeLists.txt Defines the source files for the RE2 testing library. ```cmake set(TESTING_SOURCES re2/testing/backtrack.cc re2/testing/dump.cc re2/testing/exhaustive_tester.cc re2/testing/null_walker.cc re2/testing/regexp_generator.cc re2/testing/string_generator.cc re2/testing/tester.cc util/pcre.cc ) add_library(testing ${TESTING_SOURCES}) ``` -------------------------------- ### RE2::FullMatch - Complete Text Matching in C++ Source: https://context7.com/google/re2/llms.txt Use RE2::FullMatch to verify if the entire input string matches a given regular expression pattern. It supports automatic type conversion for captured groups and can utilize pre-compiled RE2 objects for performance. ```cpp #include #include #include int main() { // Simple pattern matching assert(RE2::FullMatch("hello", "h.*o")); // true - exact match assert(!RE2::FullMatch("hello", "e")); // false - must match entire string // Extract submatches into variables int port; std::string host; assert(RE2::FullMatch("ruby:1234", "(\w+):(\d+)", &host, &port)); // host == "ruby", port == 1234 // Skip captures with NULL int value; assert(RE2::FullMatch("key:5678", "(\w+):(\d+)", (void*)NULL, &value)); // value == 5678 // Integer overflow causes failure int small; assert(!RE2::FullMatch("ruby:123456789123", "\w+:(\d+)", &small)); // Using pre-compiled RE2 for better performance RE2 pattern("(\w+):(\d+)"); assert(pattern.ok()); // Check compilation succeeded assert(RE2::FullMatch("test:42", pattern, &host, &port)); return 0; } ``` -------------------------------- ### RE2 Full and Partial Matching in C++ Source: https://github.com/google/re2/blob/main/README.md Use RE2::FullMatch to ensure the entire input string matches the regex, and RE2::PartialMatch to find the leftmost-longest substring match. Both functions require the regex to be compiled. ```cpp assert(RE2::FullMatch("hello", "h.*o")) assert(!RE2::FullMatch("hello", "e")) assert(RE2::PartialMatch("hello", "h.*o")) assert(RE2::PartialMatch("hello", "e")) ``` -------------------------------- ### Parse Numbers in Different Bases with RE2 Source: https://context7.com/google/re2/llms.txt Use `RE2::Hex()`, `RE2::Octal()`, and `RE2::CRadix()` to parse numbers in hexadecimal, octal, and C-style formats respectively. Ensure the input string and regex pattern are correctly formatted for each number type. ```cpp #include #include int main() { int decimal, hex, octal, c_style; // Parse numbers in different bases assert(RE2::FullMatch("100 40 0100 0x40", "(\S+) (\S+) (\S+) (\S+)", &decimal, // Parsed as base-10: 100 RE2::Hex(&hex), // Parsed as base-16: 64 (0x40) RE2::Octal(&octal), // Parsed as base-8: 64 (0100) RE2::CRadix(&c_style))); // C-style: 64 (0x40 prefix detected) std::cout << "Decimal: " << decimal << std::endl; // 100 std::cout << "Hex: " << hex << std::endl; // 64 std::cout << "Octal: " << octal << std::endl; // 64 std::cout << "C-style: " << c_style << std::endl; // 64 // CRadix handles various C-style number formats int values[4]; assert(RE2::FullMatch("42 0x2A 052 0b101010", "(\S+) (\S+) (\S+) (\S+)", RE2::CRadix(&values[0]), // decimal 42 RE2::CRadix(&values[1]), // hex 42 (0x2A) RE2::CRadix(&values[2]), // octal 42 (052) RE2::CRadix(&values[3]))); // binary not supported, parsed as 0 // Hex color parsing int r, g, b; assert(RE2::FullMatch("#FF8800", "#([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})", RE2::Hex(&r), RE2::Hex(&g), RE2::Hex(&b))); std::cout << "RGB: " << r << ", " << g << ", " << b << std::endl; // RGB: 255, 136, 0 return 0; } ``` -------------------------------- ### Perl-compatible Control Flow Source: https://github.com/google/re2/blob/main/doc/syntax.html These constructs control the flow of the regex matching process, similar to Prolog or other advanced engines. ```regex (*ACCEPT) ``` ```regex (*COMMIT) ``` ```regex (*F) ``` ```regex (*FAIL) ``` ```regex (*MARK) ``` ```regex (*PRUNE) ``` ```regex (*SKIP) ``` ```regex (*THEN) ``` -------------------------------- ### Extract and Reformat with RE2::Extract Source: https://context7.com/google/re2/llms.txt Utilize RE2::Extract to capture parts of a string based on a pattern and rewrite them according to a specified format string. Backreferences are used for substitution. ```cpp #include #include #include int main() { std::string out; // Extract and reformat matched content RE2::Extract("boris@kremlin.ru", "(.*)@([^"]*)", "\2!\1", &out); // out == "kremlin!boris" // Extract domain from URL std::string domain; RE2::Extract("https://www.example.com/path/to/page", "https?://([^/]+)", "\1", &domain); // domain == "www.example.com" // Format extracted date std::string formatted; RE2::Extract("Date: 2024-01-15", "(\d{4})-(\d{2})-(\d{2})", "\2/\3/\1", &formatted); // formatted == "01/15/2024" // Extract with static prefix/suffix std::string result; RE2::Extract("Error code: 404", "code: (\d+)", "HTTP_\1", &result); // result == "HTTP_404" return 0; } ``` -------------------------------- ### Set C++ Standard for Testing Library Source: https://github.com/google/re2/blob/main/CMakeLists.txt Specifies the C++ compilation features for the testing library. ```cmake target_compile_features(testing PUBLIC ${RE2_CXX_VERSION}) ``` -------------------------------- ### Find GTest Package Source: https://github.com/google/re2/blob/main/CMakeLists.txt Finds the GTest package if it's not already found. ```cmake if(NOT TARGET GTest::gtest) find_package(GTest REQUIRED) endif() ``` -------------------------------- ### Supported Anchor Points Source: https://github.com/google/re2/wiki/Syntax These anchors assert positions within the text or line. The 'm' flag affects '^' and '$'. ```regex ^ ``` ```regex \A ``` ```regex \b ``` ```regex \B ``` ```regex \z ``` -------------------------------- ### Alternation and Concatenation Source: https://github.com/google/re2/wiki/Syntax Combine expressions using '|' for alternation (match either) or concatenation (match sequentially). ```regex ab|cd ``` ```regex ab* ``` ```regex e1|e2 ``` ```regex e1e2 ``` -------------------------------- ### Match Multiple Patterns Efficiently with RE2::Set Source: https://context7.com/google/re2/llms.txt Use RE2::Set to match text against a collection of regular expressions simultaneously. This is efficient for tasks like pattern classification or multi-pattern searching, returning the indices of all matching patterns. ```cpp #include #include #include #include #include int main() { // Create a set for unanchored (substring) matching RE2::Set s(RE2::DefaultOptions, RE2::UNANCHORED); // Add patterns (returns index or -1 on error) std::string error; int idx0 = s.Add("\\d+", &error); // Index 0: numbers int idx1 = s.Add("[a-z]+", &error); // Index 1: lowercase words int idx2 = s.Add("[A-Z]+", &error); // Index 2: uppercase words int idx3 = s.Add("\\w+@\\w+\\.\\w+", &error); // Index 3: emails // Compile before matching (required) if (!s.Compile()) { std::cerr << "Compile failed" << std::endl; return 1; } // Match and get indices of matching patterns std::vector matches; s.Match("Hello World 123", &matches); // matches contains: 0 (numbers), 1 (lowercase), 2 (uppercase) std::cout << "Matched patterns: "; for (int idx : matches) { std::cout << idx << " "; } std::cout << std::endl; // Check specific text matches.clear(); s.Match("user@example.com", &matches); // matches contains: 1 (lowercase), 3 (email) // Use with error info for debugging RE2::Set::ErrorInfo error_info; bool found = s.Match("!!!!", &matches, &error_info); if (!found && error_info.kind != RE2::Set::kNoError) { std::cerr << "Match error occurred" << std::endl; } return 0; } ``` -------------------------------- ### RE2 Constructor with Quiet Option Source: https://github.com/google/re2/blob/main/README.md Use the RE2::Quiet option to silence error messages when a regular expression fails to parse. You can check re.ok() to verify success and re.error() for details. ```cpp RE2 re("(ab", RE2::Quiet); // don't write to stderr for parser failure assert(!re.ok()); // can check re.error() for details ``` -------------------------------- ### RE2 Copyright Header Source: https://github.com/google/re2/wiki/Contribute The standard copyright header to include at the beginning of files in the RE2 repository. It specifies ownership and licensing information. ```c++ // Copyright 2010 The RE2 Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. ``` -------------------------------- ### Unsupported Grouping Forms Source: https://github.com/google/re2/wiki/Syntax These grouping syntaxes are not supported by RE2. Note the specific VIM and PCRE syntaxes that are excluded. ```regex (?'name're) ``` ```regex (?#text) ``` ```regex (?|x|y|z) ``` ```regex (?>re) ``` ```regex re@> ``` ```regex %(re) ``` -------------------------------- ### Character Classes Source: https://github.com/google/re2/wiki/Syntax Match a single character from a set using square brackets. Negate the set with '^'. ```regex [xyz] ``` ```regex [^xyz] ``` -------------------------------- ### Extract All Words with RE2::FindAndConsume Source: https://context7.com/google/re2/llms.txt Use RE2::FindAndConsume to iteratively extract all occurrences of a pattern (e.g., words) from a string. The input string view is advanced past each match. ```cpp #include #include #include #include #include int main() { // Extract all words from text std::string text = "Hello world! This is a test."; absl::string_view input(text); std::string word; std::vector words; while (RE2::FindAndConsume(&input, "(\w+)", &word)) { words.push_back(word); } // words = {"Hello", "world", "This", "is", "a", "test"} // Extract all URLs from document std::string doc = "Visit https://google.com or http://example.org for info"; absl::string_view doc_view(doc); std::string url; while (RE2::FindAndConsume(&doc_view, "(https?://[\w./]+)", &url)) { std::cout << "Found URL: " << url << std::endl; } // Output: // Found URL: https://google.com // Found URL: http://example.org // Extract all numbers with context std::string data = "price: $42.50, quantity: 100, total: $4250.00"; absl::string_view data_view(data); std::string label; double amount; while (RE2::FindAndConsume(&data_view, "(\w+):\s*\$?([\d.]+)", &label, &amount)) { std::cout << label << " = " << amount << std::endl; } return 0; } ``` -------------------------------- ### Unsupported Repetition Forms Source: https://github.com/google/re2/wiki/Syntax These forms of repetition are not supported in RE2. Use standard quantifiers instead. ```regex x{-} ``` ```regex x{-n} ``` ```regex x= ``` -------------------------------- ### Any Character Match Source: https://github.com/google/re2/wiki/Syntax The '.' metacharacter matches any single character, including newline if the 's' flag is enabled. ```regex . ``` -------------------------------- ### RE2 Pre-compiled Regex Matching in C++ Source: https://github.com/google/re2/blob/main/README.md Compile a regular expression once into an RE2 object for repeated use. This improves performance by avoiding recompilation on each match attempt. Check re.ok() after compilation. ```cpp RE2 re("(\w+):(\d+)"); assert(re.ok()); // compiled; if not, see re.error(); assert(RE2::FullMatch("ruby:1234", re, &s, &i)); assert(RE2::FullMatch("ruby:1234", re, &s)); assert(RE2::FullMatch("ruby:1234", re, (void*)NULL, &i)); assert(!RE2::FullMatch("ruby:123456789123", re, &s, &i)); ``` -------------------------------- ### Set RE2 Target Properties Source: https://github.com/google/re2/blob/main/CMakeLists.txt Configures properties for the RE2 library target, including public headers and shared object version. ```cmake set_target_properties(re2 PROPERTIES PUBLIC_HEADER "${RE2_HEADERS}") set_target_properties(re2 PROPERTIES SOVERSION ${SONAME} VERSION ${SONAME}.0.0) ``` -------------------------------- ### RE2::Consume - Incremental Text Scanning Source: https://context7.com/google/re2/llms.txt The RE2::Consume function matches regular expressions at the front of a string_view and advances it past the matched text. This is useful for tokenizing or parsing structured text incrementally. ```APIDOC ## RE2::Consume - Incremental Text Scanning ### Description Matches regular expressions at the front of a string_view and advances it past the matched text. This is useful for tokenizing or parsing structured text incrementally. ### Method `RE2::Consume` ### Parameters This function takes a pointer to a `string_view` (which will be modified), the pattern, and optionally pointers to variables to store captured groups. ### Request Example ```cpp #include #include #include #include int main() { // Parse key-value pairs std::string contents = "name = 42\ncount = 100\nmax = 999\n"; absl::string_view input(contents); std::string var; int value; while (RE2::Consume(&input, "(\w+) = (\d+)\n", &var, &value)) { std::cout << var << " -> " << value << std::endl; } // Output: // name -> 42 // count -> 100 // max -> 999 // Tokenize CSV-like data std::string csv = "apple,banana,cherry,date"; absl::string_view csv_view(csv); std::string token; // First token (no comma prefix) if (RE2::Consume(&csv_view, "([^,]+)", &token)) { std::cout << "Token: " << token << std::endl; // apple } // Remaining tokens while (RE2::Consume(&csv_view, ",([^,]+)", &token)) { std::cout << "Token: " << token << std::endl; // banana, cherry, date } return 0; } ``` ### Response Returns `true` if the pattern matches at the beginning of the `string_view` and the `string_view` is advanced. Returns `false` otherwise. ``` -------------------------------- ### RE2 Character Classes Source: https://github.com/google/re2/blob/main/doc/syntax.html These character classes provide shorthand for common character sets. They are equivalent to the character sets shown. ```regex `\d` ``` ```regex `\D` ``` ```regex `\x` ``` ```regex `\X` ``` ```regex `\o` ``` ```regex `\O` ``` ```regex `\w` ``` ```regex `\W` ``` ```regex `\h` ``` ```regex `\H` ``` ```regex `\a` ``` ```regex `\A` ``` ```regex `\l` ``` ```regex `\L` ``` ```regex `\u` ``` ```regex `\U` ``` -------------------------------- ### Perl and ASCII Character Classes Source: https://github.com/google/re2/wiki/Syntax Utilize predefined character classes like \d for digits or [[:alpha:]] for alphabetic characters. Negated classes are also supported. ```regex \d ``` ```regex \D ``` ```regex [[:alpha:]] ``` ```regex [[:^alpha:]] ``` -------------------------------- ### Link RE2 to ICU Source: https://github.com/google/re2/blob/main/CMakeLists.txt Links the RE2 library to the ICU library if RE2_USE_ICU is enabled. ```cmake if(RE2_USE_ICU) target_link_libraries(re2 PUBLIC ICU::uc) endif() ```