'How to replace all '\n' character after 'word' with 'comma' character
Trying to replace all the \n character after the word 'key2:' pattern with comma.
Input String:
key1:value1\nkey2:value2\nvalue22\nvalue222
Expected:
key1:value1\nkey2:value2,value22,value222
Tried:
r'key2:(\n*$)' replace with ','
any suggestions on how can i replace it using regex! from https://rustexp.lpil.uk/
Solution 1:[1]
I don't think this can easily be done with regex, so I'd propose a simpler way:
let mut s = String::from("key1:value1\nkey2:value2\nvalue22\nvalue222");
let expected = "key1:value1\nkey2:value2,value22,value222";
let key2 = "key2";
let substr_index = s.find(key2).unwrap() + key2.len();
let commas = s[substr_index..].replace("\n", ",");
s.replace_range(substr_index.., &commas);
assert_eq!(s, expected);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | isaactfa |