### Full String Matching with Nim Regex Source: https://context7.com/nitely/nim-regex/llms.txt Covers matching an entire string against a regex pattern from start to end using `match`. Includes examples for simple matches, capturing groups, and named captures. The `RegexMatch2` object stores match details. ```nim import regex var m = RegexMatch2() # Simple match doAssert "abc".match(re2"abc", m) doAssert not "abcd".match(re2"abc", m) # Match with captures doAssert "nim-regex-2023".match(re2"(\w+)-(\w+)-(\d+)", m) doAssert "nim-regex-2023"[m.group(0)] == "nim" doAssert "nim-regex-2023"[m.group(1)] == "regex" doAssert "nim-regex-2023"[m.group(2)] == "2023" # Named captures let text = "hello world" doAssert text.match(re2"(?P\w+) (?P\w+)", m) doAssert text[m.group("greet")] == "hello" doAssert text[m.group("who")] == "world" ``` -------------------------------- ### Find First Regex Match in Nim Source: https://context7.com/nitely/nim-regex/llms.txt Demonstrates how to find the first occurrence of a regex pattern within a string using the `find` function. Examples show extracting captured groups and using the `start` parameter to specify a search offset. The `m.boundaries` property provides the matched substring. ```nim import regex var m = RegexMatch2() # Find email in text let text = "Contact us at support@example.com for help" doAssert text.find(re2"(\w+)@(\w+\.\w+)", m) doAssert text[m.boundaries] == "support@example.com" doAssert text[m.group(0)] == "support" doAssert text[m.group(1)] == "example.com" # Find with start position doAssert "abc bc bc".find(re2"bc", m) doAssert m.boundaries == 1..2 doAssert "abc bc bc".find(re2"bc", m, start=3) doAssert m.boundaries == 4..5 ``` -------------------------------- ### Split Strings Using Regex Delimiters in Nim Source: https://context7.com/nitely/nim-regex/llms.txt Demonstrates splitting strings based on regex patterns using `split` and `splitIncl`. Covers splitting by multiple characters, whitespace, and includes examples of splitting with captures to retain delimiters. Also shows splitting on line boundaries. ```nim import regex # Split by multiple delimiters let text = "apple,banana;cherry:date" let fruits = split(text, re2"[,;:]") doAssert fruits == @["apple", "banana", "cherry", "date"] # Split with whitespace let numbers = "1 2 3 4" doAssert split(numbers, re2"\s+") == @["1", "2", "3", "4"] # Split including captures (delimiters) let csv = "a,b,c" doAssert splitIncl(csv, re2"(,)") == @["a", ",", "b", ",", "c"] # Split on line boundaries let lines = "line1\nline2\nline3" doAssert split(lines, re2"(?m)^ Địa chỉ IP : [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}")[1..^1] == @["line2\n", "line3"] ``` -------------------------------- ### Regex Boundary Checking (startsWith/endsWith) in Nim Source: https://context7.com/nitely/nim-regex/llms.txt Shows how to check if a string begins or ends with a regex pattern using `startsWith` and `endsWith`. Includes examples with optional patterns (like `s?`), checking with an offset, and matching specific file extensions. ```nim import regex # Check start of string doAssert "https://example.com".startsWith(re2"https?://") doAssert not "ftp://example.com".startsWith(re2"https?://") # Check with offset doAssert "abc".startsWith(re2"bc", start=1) # Check end of string doAssert "document.txt".endsWith(re2"\.\w{3}") doAssert not "document.text".endsWith(re2"\.\w{3}") ``` -------------------------------- ### Match Macro for Performance in Nim Source: https://context7.com/nitely/nim-regex/llms.txt Introduces the compile-time `match` macro (`rex`) for zero-overhead regex matching and validation. Demonstrates its use for extracting captured groups, with lookarounds, and reusable patterns via templates. Dependencies: `regex` module. Input: String, Regex pattern. Output: Boolean, captured groups. ```nim import regex # Macro version - faster, compile-time checked var matched = false match "abc123", rex"([a-z]+)(\d+)": doAssert matches == @["abc", "123"] matched = true doAssert matched # Match with lookarounds match "hello world", rex"(\w+)(?=\s)": doAssert matches == @["hello"] # Template usage for reusable patterns template emailRegex: untyped = rex"(\w+)@(\w+\.\w+)" match "test@example.com", emailRegex: doAssert matches[0] == "test" doAssert matches[1] == "example.com" ``` -------------------------------- ### Compile Regular Expression Patterns in Nim Source: https://context7.com/nitely/nim-regex/llms.txt Demonstrates compiling regex patterns at compile-time using `re2` and at runtime with flags. It highlights the use of raw string literals with the `rex` macro for convenience. Supports PCRE-compatible syntax and options like caseless and multiline matching. ```nim import regex # Compile at compile-time (preferred) const emailPattern = re2(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}") doAssert "user@example.com".match(emailPattern) # Compile at runtime with flags let pattern = re2(r"\d+", {regexCaseless, regexMultiline}) var m = RegexMatch2() doAssert "ABC123".find(pattern, m) # With raw string literal for macro let text = "test@email.com" match text, rex"(\w+)@(\w+\.\w+)": doAssert matches == @["test", "email.com"] ``` -------------------------------- ### Replace Regex Matches in Nim Source: https://context7.com/nitely/nim-regex/llms.txt Explains string replacement using `replace` with regex patterns. Includes simple substitutions, using capture groups in replacements, limiting the number of replacements, and using a callback function for complex replacements. ```nim import regex # Simple replacement doAssert "hello world".replace(re2"world", "Nim") == "hello Nim" # With capture groups let text = "Error: code 123, line 456" let result = text.replace(re2"code (\d+), line (\d+)", "line $2, code $1") doAssert result == "Error: line 456, code 123" # Limit replacements doAssert "aaa".replace(re2"a", "b", 2) == "bba" # Using callback function proc censor(m: RegexMatch2, s: string): string = if s[m.group(0)].len > 3: return "****" return s[m.group(0)] let censored = "hello secret world".replace(re2"(\w+)", censor) doAssert censored == "**** **** ****" ``` -------------------------------- ### Find All Regex Matches in Nim Source: https://context7.com/nitely/nim-regex/llms.txt Illustrates finding all non-overlapping occurrences of a pattern in a string using `findAll` and `findAllBounds`. Shows how to extract matched substrings, captured groups, and boundaries. Useful for iterating through all matches in a text. ```nim import regex # Find all email addresses let text = """ Contact: john@example.com Support: help@example.com Sales: sales@example.com """ var emails = newSeq[string]() for m in findAll(text, re2"(\w+)@(\w+\.\w+)"): emails.add text[m.boundaries] doAssert emails == @["john@example.com", "help@example.com", "sales@example.com"] # Get just the boundaries let bounds = findAllBounds(text, re2"\w+@\w+\.\w+") doAssert bounds.len == 3 # Extract usernames with captures var usernames = newSeq[string]() for m in findAll(text, re2"(\w+)@\w+\.\w+"): usernames.add text[m.group(0)] doAssert usernames == @["john", "help", "sales"] ``` -------------------------------- ### Error Handling and Validation in Nim Regex Source: https://context7.com/nitely/nim-regex/llms.txt Covers methods for handling regex compilation errors and validating inputs. It shows compile-time checking, runtime `try-except` blocks for `RegexError`, checking regex initialization status, and validating UTF-8 input before processing. Dependencies: `regex`, `unicode` modules. Input: String, Regex. Output: Boolean, error messages. ```nim import regex import unicode # Compile-time error checking (preferred) # const badPattern = re2("[") # Compile error: Invalid set # Runtime error handling try: let pattern = re2("[") doAssert false, "Should have raised" except RegexError as e: doAssert "Invalid set" in e.msg # Check if regex is initialized var pattern: Regex2 doAssert not pattern.isInitialized pattern = re2"test" doAssert pattern.isInitialized # Validate UTF-8 input (automatic in debug mode) let text = "\xf8\xa1\xa1\xa1\xa1" if validateUtf8(text) == -1: # Safe to use with regex discard else: # Invalid UTF-8, use arbitrary bytes mode doAssert text.match(re2(r".+", {regexArbitraryBytes})) # Escape special characters let userInput = "test.txt" let escaped = escapeRe(userInput) # "test\\.txt" doAssert "test.txt".match(re2(escaped)) ``` -------------------------------- ### Nim: Basic Regex Match Scenario Source: https://context7.com/nitely/nim-regex/llms.txt Demonstrates a basic scenario in Nim where a regular expression is used to search for a pattern ('abc') within a string ('xyz'). It shows how to check if a match was found using a boolean flag. This snippet highlights the core matching functionality. ```nim var found = false match "xyz", rex"abc": found = true doAssert not found ``` -------------------------------- ### Basic Pattern Matching in Nim Source: https://context7.com/nitely/nim-regex/llms.txt Demonstrates fundamental regex pattern matching using the `re2` macro. It checks for the presence and absence of simple patterns within strings. Dependencies: `regex` module. Input: String. Output: Boolean. ```nim doAssert re2"\d+" in "abc123def" doAssert re2"xyz" notin "abc123def" ``` -------------------------------- ### Unicode and Character Classes in Nim Regex Source: https://context7.com/nitely/nim-regex/llms.txt Illustrates the use of Unicode character classes and properties for matching international characters and symbols. It also covers ASCII mode (`(?-u)`) and handling multi-byte Unicode sequences. Dependencies: `regex`, `unicode` modules. Input: String, Regex. Output: Boolean, match boundaries. ```nim import regex import unicode # Unicode character classes doAssert "Ǝ弢Ⓐ".match(re2"\w+") # Unicode word characters doAssert "弢".match(re2"\p{L}") # Unicode letters doAssert "۲".match(re2"\d") # Unicode digits # ASCII mode doAssert "abc123".match(re2"(?-u)[\w]+") # ASCII only doAssert not "弢".match(re2"(?-u)\w") # Character properties doAssert "a".match(re2"\p{Ll}") # Lowercase letter doAssert "A".match(re2"\p{Lu}") # Uppercase letter doAssert "1".match(re2"\p{Nd}") # Decimal number doAssert "_".match(re2"\p{Pc}") # Connector punctuation # Multi-byte Unicode var m = RegexMatch2() let text = "①②③" doAssert text.find(re2"①②③", m) doAssert m.boundaries == 0..