Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a string located between

Here is my problem: in a variable that is text and contains commas, I try to delete only the commas located between two strings (in fact [ and ]). For example using the following string:

input =  "The sun shines, that's fine [not, for, everyone] and if it rains, it Will Be better."
output = "The sun shines, that's fine [not for everyone] and if it rains, it Will Be better."

I know how to use .replace for the whole variable, but I can not do it for a part of it. There are some topics approaching on this site, but I did not manage to exploit them for my own question, e.g.:

  • Repeatedly extract a line between two delimiters in a text file, Python
  • Python finding substring between certain characters using regex and replace()
  • replace string between two quotes
like image 550
user1453786 Avatar asked Jun 19 '12 07:06

user1453786


People also ask

How do I replace a string between two strings in Java?

Using replaceAll() The first parameter takes in a regular expression while the second takes in a string with the replacement value. String start = "\\{"; String end = "\\}"; String updatedUrl = url. replaceAll(start + ".

How do you replace a certain place in a string in Python?

Strings in Python are immutable meaning you cannot replace parts of them. You can however create a new string that is modified.


2 Answers

import re
Variable = "The sun shines, that's fine [not, for, everyone] and if it rains, it Will Be better."
Variable1 = re.sub("\[[^]]*\]", lambda x:x.group(0).replace(',',''), Variable)

First you need to find the parts of the string that need to be rewritten (you do this with re.sub). Then you rewrite that parts.

The function var1 = re.sub("re", fun, var) means: find all substrings in te variable var that conform to "re"; process them with the function fun; return the result; the result will be saved to the var1 variable.

The regular expression "[[^]]*]" means: find substrings that start with [ (\[ in re), contain everything except ] ([^]]* in re) and end with ] (\] in re).

For every found occurrence run a function that convert this occurrence to something new. The function is:

lambda x: group(0).replace(',', '')

That means: take the string that found (group(0)), replace ',' with '' (remove , in other words) and return the result.

like image 164
Igor Chubin Avatar answered Oct 05 '22 04:10

Igor Chubin


You can use an expression like this to match them (if the brackets are balanced):

,(?=[^][]*\])

Used something like:

re.sub(r",(?=[^][]*\])", "", str)
like image 39
Qtax Avatar answered Oct 05 '22 04:10

Qtax