Skip to content

expr: Fix parsing negated character classes "[^a]" #7884

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
10 changes: 8 additions & 2 deletions src/uu/expr/src/syntax_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,13 +166,19 @@ impl StringOp {
};

// Handle the rest of the input pattern.
// Escape characters that should be handled literally within the pattern.
// Escaped previous character should not affect the current.
let mut prev = first.unwrap_or_default();
let mut prev_is_escaped = false;
for curr in pattern_chars {
match curr {
'^' if prev != '\\' => re_string.push_str(r"\^"),
// Carets are interpreted literally, unless used as character class negation "[^a]"
'^' if prev_is_escaped || !matches!(prev, '\\' | '[') => {
re_string.push_str(r"\^");
}
char => re_string.push(char),
}

prev_is_escaped = prev == '\\' && !prev_is_escaped;
prev = curr;
}

Expand Down
24 changes: 24 additions & 0 deletions tests/by-util/test_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,26 @@ fn test_regex() {
.args(&["^^^^^^^^^", ":", "^^^"])
.succeeds()
.stdout_only("2\n");
new_ucmd!()
.args(&["ab[^c]", ":", "ab[^c]"])
.succeeds()
.stdout_only("3\n"); // Matches "ab["
new_ucmd!()
.args(&["ab[^c]", ":", "ab\\[^c]"])
.succeeds()
.stdout_only("6\n");
new_ucmd!()
.args(&["[^a]", ":", "\\[^a]"])
.succeeds()
.stdout_only("4\n");
new_ucmd!()
.args(&["\\a", ":", "\\\\[^^]"])
.succeeds()
.stdout_only("2\n");
new_ucmd!()
.args(&["^a", ":", "^^[^^]"])
.succeeds()
.stdout_only("2\n");
new_ucmd!()
.args(&["-5", ":", "-\\{0,1\\}[0-9]*$"])
.succeeds()
Expand All @@ -319,6 +339,10 @@ fn test_regex() {
.args(&["^abc", ":", "^abc"])
.fails()
.stdout_only("0\n");
new_ucmd!()
.args(&["abc", ":", "ab[^c]"])
.fails()
.stdout_only("0\n");
}

#[test]
Expand Down
Loading