AcidHawk
AcidHawk

Reputation: 566

Regex to remove spaces from Key but not Value

I have the following JSON object

{
    "Submitter":"Fred",
    "Create Date":"2019-11-05T11:31:58.000+0000",
    "Assigned To":"Some Person",
    "Last Modified By":"[email protected]",
    "A String of Four": "A String with 4 words and 3 spaces",
    "Another Test": "Four Words Appear Here",
}

I want to remove all the spaces from the Keys (E.g. "Created Date", and "A String of Four" etc) However I do not want to remove the spaces in the values.

I have tried the following, but this picks up all the spaces except those that follow a quote and a colon (":)

(?!")\s(?!")(?!:)

I also tried

\s(?=\w*\":)

but this only picks up the last space before a word ending with a quote and a colon (":) and none of the other spaces in the Key.

My next attempt and the one I think I am getting closest with is this:

(?<=").*?(?=\w*":)|(?<!":)(?!.*?)(?=\w*)

I am testing with https://regex101.com/

Upvotes: 2

Views: 966

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You can probably try the following expression as a quick fix granted the JSON you need to fix is in the format you have shown (it might fail to work with other JSONs):

\s(?=[^"]*":\s*")

See the regex demo

Details

  • \s - a whitespace
  • (?=[^"]*":\s*") - a positive lookahead that, immediately to the right of the current position, requires
    • [^"]* - zero or more chars other than "
    • ": - ": string
    • \s* - 0+ whitespaces
    • " - a double quote.

Upvotes: 1

Related Questions