-3

Newbie to Regex and would like to convert all blank spaces into underscore for all occurrences that a string have between square brackets.

Example:

Original String: "This is a text [this is another text] but there is [more text] here"

Desired output: "This is a text [this_is_another_text] but there is [more_text] here"

Appreciate any help!

anubhava
  • 761,203
  • 64
  • 569
  • 643
ticorunner
  • 37
  • 5
  • 1
    "Regex" differs between libraries (and thus languages) -- syntax is also tied to an implementation (similar to SQL and the differences in SQL dialects between, say, Oracle and Microsoft SQL implementations). You should tag the question with the library you are using, as even the computational power of individual implementations depends on how much "extensions" they support (and also affect the optimal way to express regex strings/expressions). – CinchBlue Jul 20 '22 at 16:37
  • what langaiuage are you trying to do this in. it differs. also regex101.com is a great scratch pad. I started for you https://regex101.com/r/v5hBOv/1 – Josh Beauregard Jul 20 '22 at 17:33
  • Javascript would be in charge of running this. If helpful, this is where I'm testing: https://www.regextester.com/index.php?fam=123332 – ticorunner Jul 20 '22 at 17:34
  • I got the piece to identify all occurrences of text between square brackets, but having hard time with adding the code to replace the spaces with underscores: Regex Code: \[.*?\] – ticorunner Jul 20 '22 at 17:47
  • 1
    Something like `result = subject.replace(/\s+(?=[^[\]]*])/g, "_");` will be enough. – Wiktor Stribiżew Jul 20 '22 at 18:13

1 Answers1

0

You can try this:

import re
a ='This is a text [this is another text] but there is [more text] here'
match= re.sub('\[(.*?)\]', lambda m: m[0].replace(' ','_'),a)
print(match)

output:

This is a text [this_is_another_text] but there is [more_text] here
Hiral Talsaniya
  • 376
  • 1
  • 5