Home > database >  Regular Expression to remove every whitespace which is not after a comma
Regular Expression to remove every whitespace which is not after a comma

Time:10-31

i want to replace remove/replace every whitespace in a string which is not after a comma. I already searched for a suitable regex but i did not find one. Here is a sample of the strings i want to modify:

{id=565189.0, server=Ealyn, merchantName=Nox, activeMerchants=[{id=f01b617d-2dc7-4597-2297-08dabad9a125, name=Nox, zone=Nebel horn, card={name=Bergstrom, rarity=2.0}, rapport={name=Energy X7 Capsule, rarity=3.0}, votes=0.0}]}

should change to (_ trough replace)

{id=565189.0, server=Ealyn, merchantName=Nox, activeMerchants=[{id=f01b617d-2dc7-4597-2297-08dabad9a125, name=Nox, zone=Nebel_horn, card={name=Bergstrom, rarity=2.0}, rapport={name=Energy_X7_Capsule, rarity=3.0}, votes=0.0}]}

Can someone with a high knowledge then me over regular expression's create one for this case? Thanks in advance

I already tried this expression:

(^|[^,])\\s 

.. but it always removed a character with the whitespace

CodePudding user response:

This can be accomplished using a negative lookbehind:

(?<!,)\\s 

The Output:

{id=565189.0, server=Ealyn, merchantName=Nox, activeMerchants=[{id=f01b617d-2dc7-4597-2297-08dabad9a125, name=Nox, zone=Nebel_horn, card={name=Bergstrom, rarity=2.0}, rapport={name=Energy_X7_Capsule, rarity=3.0}, votes=0.0}]}

CodePudding user response:

This worked for me. The trick is to choose the group you want to keep and reference it in the replacement parameter of the replaceAll method.

  public static void main(String[] args) {
    var before = "{id=565189.0, server=Ealyn, merchantName=Nox, activeMerchants=[{id=f01b617d-2dc7-4597-2297-08dabad9a125, name=Nox, zone=Nebel horn, card={name=Bergstrom, rarity=2.0}, rapport={name=Energy X7 Capsule, rarity=3.0}, votes=0.0}]}";
    var after = before.replaceAll("([^,])\\s ", "$1");
    System.out.println(before);
    System.out.println(after);
  }
  • Related