Nico G.
Nico G.

Reputation: 517

RegEx: match line breaks or spaces between square brackets

How can I find all line breaks or spaces that are inside square brackets?

I have the following string:

{
  "decay_id": {
    "int_only": true,
    "feature_type": "categorical",
    "category_values": [
      0,
      1
    ],
    "category_names": [
      "d1",
      "d2"
    ]
  }
}

And I want to delete line breaks and spaces so that I get:

{
  "decay_id": {
    "int_only": true,
    "feature_type": "categorical",
    "category_values": [0,1],
    "category_names": ["d1","d2"]
  }
}

How can I use RegEx (and Python) to do this?

Something like:

import re

output = re.sub("some RegEx", "", input)

Upvotes: 0

Views: 74

Answers (1)

Ryszard Czech
Ryszard Czech

Reputation: 18621

Use

import re

output = re.sub(r"\[[^][]*]", lambda z: re.sub(r'\s+', '', z.group()), input)

See Python code

Results:

{
  "decay_id": {
    "int_only": true,
    "feature_type": "categorical",
    "category_values": [0,1],
    "category_names": ["d1","d2"]
  }
}

Upvotes: 1

Related Questions