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.
This commit is contained in:
Ade Attwood 2024-05-11 21:45:21 +01:00
parent 93e64fa8db
commit b098c75cb5
2 changed files with 10 additions and 1 deletions

View file

@ -17,7 +17,10 @@ fn concert_replacement(original: &str, replacement: &str) -> String {
pub fn replace(search: &String, replace: String, input: String) -> String { pub fn replace(search: &String, replace: String, input: String) -> String {
let mut index = 0; let mut index = 0;
let mut output = input; 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) { while let Some(search_match) = search_pattern.find_at(&output, index) {
let start = search_match.start(); let start = search_match.start();

View file

@ -17,3 +17,9 @@ Feature: Regex search and replace
And Replace is 'Hello ${1}s' And Replace is 'Hello ${1}s'
And Input is 'Hello world' And Input is 'Hello world'
Then Output is 'Hello worlds' 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'