2

I have the following line:

{ "diameter":6 }   { 60 }  {"din":Anchor-1 R 6/5SPx3} {"length":30 } { Impact anchor } {"diameter":6 } { Online:0 } {, de03042 }

I'm trying to remove the following:

  • whitespace between each opening and closing braces e.g. { "diameter":6 } { 60 } changes to { "diameter":6 }{ 60 }
  • Any opened and closed brace that has a number inside it. In this case, { 60} will disappear from the output.

I'm using the following pattern but it's not giving the desired output.

s = Regex.Replace(s, @"\s+[{}^]", ""); //Remove whitespace between each element

s = Regex.Replace(s, @"{{ [0-9^}]*}\}", ""); // Remove { 60 }

Desired output:

{ "diameter":6 }{"din":Anchor-1 R 6/5SPx3}{"length":30 }{ Impact anchor } {"diameter":6 }{ Online:0 }{, de03042 }

Current Output:

{ "diameter":660"din":Anchor-1 R 6/5SPx3}"length":30 Impact anchor HPS-1 R 6/5SPx3"diameter":6 Online:0 de03042

Could anyone please point out what's wrong with my patterns?

1
  • @Liam added the output. Commented Jul 21, 2015 at 11:51

1 Answer 1

5

You can use the following regex:

(?<=})\s*(?={)|{\s*\d+\s*}

Replace with string.Empty.

See demo

Result:

enter image description here

REGEX EXPLANATION:

The pattern contains 2 alternatives (note the | alternation operator).

  1. (?<=})\s*(?={):

    • (?<=}) - a positive lookbehind that makes sure there is a }
    • \s* - 0 or more (*) whitespace (\s)
    • (?={) - a positive lookahead that makes sure there is { right after the whitespace
  2. {\s*\d+\s*}:

    • { - matches a { literally
    • \s* - 0 or more (*) whitespace (\s)
    • \d+ - 1 or more digits
    • \s* - 0 or more (*) whitespace (\s)
    • } - matches a } literally.
Sign up to request clarification or add additional context in comments.

3 Comments

Better than my answer!
@Liam, what was yours? I did not see :( MaskedAfrican: Actually, we can use alternation here with 1 regex since you replace with empty string. Otherwise, it would be more complicated, and would need code adjustment.
I deleted it, yours is much cleaner, I was using multiple patterns!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.