-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
A convenience function, which does the slicing and position adjustments for you, to match at a given position within the haystack string.
- Loading branch information
Showing
3 changed files
with
32 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -124,6 +124,25 @@ pub fn SizedRegex(ops: comptime_int, char_sets: comptime_int) type { | |
} | ||
} | ||
|
||
/// Match a regex pattern in `haystack` after `pos`. Returns a `Match` | ||
/// if the pattern is found. | ||
pub fn matchPos(regex: *const SizedRegexT, pos: usize, haystack: []const u8) ?Match { | ||
const substack = haystack[pos..]; | ||
if (substack.len == 0) return null; | ||
const maybe_matched = regex.matchInternal(substack); | ||
if (maybe_matched) |m| { | ||
const m1 = pos + m[0]; | ||
const m2 = pos + m[1]; | ||
return Match{ | ||
.slice = haystack[m1..m2], | ||
.start = m1, | ||
.end = m2, | ||
}; | ||
} else { | ||
return null; | ||
} | ||
} | ||
|
||
/// Boolean test if the regex matches in the haystack. | ||
pub fn isMatch(regex: *const SizedRegexT, haystack: []const u8) bool { | ||
const maybe_matched = regex.matchInternal(haystack); | ||
|
@@ -2119,6 +2138,7 @@ test "workshop" { | |
// printRegexString("^[a-zA-Z0-9_!#$%&.-]+@([a-zA-Z0-9.-])+$"); | ||
// try testMatchAll("^[a-zA-Z0-9_!#$%&.-]+@([a-zA-Z0-9.-])+$", "[email protected]"); | ||
// | ||
try testMatchAll("(a[bc]){3,5}ac", "abacabacac"); | ||
} | ||
|
||
test "heap allocated regex and match" { | ||
|
@@ -2167,6 +2187,14 @@ test "iteration" { | |
try expectEqual(null, r_iter.next()); | ||
} | ||
|
||
test "matchPos" { | ||
const regex = Regex.compile("abcd").?; | ||
const matched = regex.matchPos(4, "abcdabcd").?; | ||
try expectEqual(4, matched.start); | ||
try expectEqualStrings("abcd", matched.slice); | ||
try expectEqual(8, matched.end); | ||
} | ||
|
||
test "comptime regex" { | ||
const comp_regex = comptime compile("foo+").?; | ||
const run_match = comp_regex.match("foofoofoo"); | ||
|