1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-27 19:17:43 +00:00

expr: Handle special cases for ^ in regex

This commit is contained in:
Teemu Pätsi 2025-05-23 15:22:18 +03:00
parent 6a828f0e74
commit f664578a4b
No known key found for this signature in database
2 changed files with 19 additions and 4 deletions

View file

@ -171,11 +171,18 @@ impl StringOp {
let mut prev_is_escaped = false;
for curr in pattern_chars {
match curr {
// Carets are interpreted literally, unless used as character class negation "[^a]"
'^' if prev_is_escaped || !matches!(prev, '\\' | '[') => {
re_string.push_str(r"\^");
'^' => match (prev, prev_is_escaped) {
// Start of a capturing group
('(', true)
// Start of an alternative pattern
| ('|', true)
// Character class negation "[^a]"
| ('[', false)
// Explicitly escaped caret
| ('\\', false) => re_string.push(curr),
_ => re_string.push_str(r"\^"),
}
char => re_string.push(char),
_ => re_string.push(curr),
}
prev_is_escaped = prev == '\\' && !prev_is_escaped;

View file

@ -282,6 +282,14 @@ fn test_regex() {
.args(&["a^b", ":", "a\\^b"])
.succeeds()
.stdout_only("3\n");
new_ucmd!()
.args(&["b", ":", "a\\|^b"])
.succeeds()
.stdout_only("1\n");
new_ucmd!()
.args(&["ab", ":", "\\(^a\\)b"])
.succeeds()
.stdout_only("a\n");
new_ucmd!()
.args(&["a$b", ":", "a\\$b"])
.succeeds()