From dc5fbc402625e36e6e0df618b4b0600341927c75 Mon Sep 17 00:00:00 2001 From: Ade Attwood Date: Sat, 11 May 2024 21:41:22 +0100 Subject: [PATCH] fix: handle invalid regex patterns by returning the input string Right now we don't want to be panicking if the user provides an invalid regex. We also don't really want to be throwing or returning an error, this will mess with any live preview that is going on in external tools. We should return the input and let any preview display the text. This will happen if the user is doing some preview as you type kind of thing. --- src/lib.rs | 5 ++++- tests/features/regex.feature | 6 ++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index ee75c56..e8d0a94 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -17,7 +17,10 @@ fn concert_replacement(original: &str, replacement: &str) -> String { pub fn replace(search: &String, replace: String, input: String) -> String { let mut index = 0; let mut output = input; - let search_pattern = Regex::new(&format!("(?i){search}")).unwrap(); + let search_pattern = match Regex::new(&format!("(?i){search}")) { + Ok(pattern) => pattern, + Err(_) => return output + }; while let Some(search_match) = search_pattern.find_at(&output, index) { let start = search_match.start(); diff --git a/tests/features/regex.feature b/tests/features/regex.feature index 0e07ec5..3e3ad5c 100644 --- a/tests/features/regex.feature +++ b/tests/features/regex.feature @@ -17,3 +17,9 @@ Feature: Regex search and replace And Replace is 'Hello ${1}s' And Input is 'Hello world' Then Output is 'Hello worlds' + + Scenario: You can search with an invalid regular expression + Given Search is '(\w+' + And Replace is 'new' + And Input is 'this is a' + Then Output is 'this is a'