1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-28 03:27:44 +00:00

expr: Handle trailing backslash error

This commit is contained in:
Teemu Pätsi 2025-05-24 01:27:09 +03:00
parent cd9ce77098
commit 4555e6fe48
No known key found for this signature in database
GPG key ID: 5494F73B045AB692
3 changed files with 28 additions and 0 deletions

View file

@ -50,6 +50,8 @@ pub enum ExprError {
UnmatchedClosingBrace,
#[error("Invalid content of \\{{\\}}")]
InvalidBracketContent,
#[error("Trailing backslash")]
TrailingBackslash,
}
impl UError for ExprError {

View file

@ -161,6 +161,7 @@ impl StringOp {
match first {
Some('^') => {} // Start of string anchor is already added
Some('*') => re_string.push_str(r"\*"),
Some('\\') if right.len() == 1 => return Err(ExprError::TrailingBackslash),
Some(char) => re_string.push(char),
None => return Ok(0.into()),
};
@ -169,6 +170,8 @@ impl StringOp {
let mut prev = first.unwrap_or_default();
let mut prev_is_escaped = false;
while let Some(curr) = pattern_chars.next() {
let curr_is_escaped = prev == '\\' && !prev_is_escaped;
match curr {
'^' => match (prev, prev_is_escaped) {
// Start of a capturing group
@ -201,6 +204,9 @@ impl StringOp {
re_string.push('$');
}
}
'\\' if !curr_is_escaped && pattern_chars.peek().is_none() => {
return Err(ExprError::TrailingBackslash);
}
_ => re_string.push(curr),
}

View file

@ -365,6 +365,26 @@ fn test_regex() {
.stdout_only("0\n");
}
#[test]
fn test_regex_trailing_backslash() {
new_ucmd!()
.args(&["\\", ":", "\\\\"])
.succeeds()
.stdout_only("1\n");
new_ucmd!()
.args(&["\\", ":", "\\"])
.fails()
.stderr_only("expr: Trailing backslash\n");
new_ucmd!()
.args(&["abc\\", ":", "abc\\\\"])
.succeeds()
.stdout_only("4\n");
new_ucmd!()
.args(&["abc\\", ":", "abc\\"])
.fails()
.stderr_only("expr: Trailing backslash\n");
}
#[test]
fn test_substr() {
new_ucmd!()