I am trying to replace a certain part of a match that a regex found. The relevant strings have the following format:
"<Random text>[Text1;Text2;....;TextN]<Random text>"
So basically there can be N Texts seperated by a ";" inside the brackets. My goal is to change the ";" into a "," (but only for the strings which are in this format) so that I can keep the ";" as a seperator for a CSV file. So the result should be:
"<Random text>[Text1,Text2,...,TextN]<Random text>"
I can match the relevant strings with something like
re.compile(r'\[".*?((;).*?){1,4}"\]')
but if I try to use the sub method it replaces the whole string.
I have searched stackoverflow and I am pretty sure that "capture groups" might be the solution but I am not really getting there. Can anyone help me?
I ONLY want to change the ";" in the ["Text1;...;TextN"]-parts of my text file.
Try this regex:
;(?=(?:(?!\[).)*])
Replace each match with a ,
Click for Demo
Explanation:
; - matches a ;(?=(?:(?!\[).)*]) - makes sure that the above ; is followed by a closing ] somewhere later in the string but before any opening bracket [
(?=....) - positive lookahead(?:(?!\[).)* - 0+ occurrences of any character which does not start with [] - matches a ]If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With