Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
expr: Handle special cases for ^ in regex
  • Loading branch information
frendsick committed May 23, 2025
commit f664578a4b781bf941231eea684673a881e1f177
15 changes: 11 additions & 4 deletions src/uu/expr/src/syntax_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
8 changes: 8 additions & 0 deletions tests/by-util/test_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down