Vadim T
Vadim T

Reputation: 528

Regex experssion replace only double sqaure brackets

How can i replace square brackets with regex expression in c#?

I'm using this expression but it doesn't work for me.

var email = Regex.Replace(emailaddress, @"[\[\]']+", "")

It replaces all the square brackets - @"[[]']+" It doesn't work for me.

This is what i need: To replace only double square brackets from each side

[[test]]@gmail.com -> [email protected]

[[[[test]]]]]@gmail.com -> [[test]]@gmail.com

[[[test]]]]]@gmail.com -> to [[email protected]]]]

[[[[test]]]]@gmail.com -> to [[[email protected]]]

I need to this check only with a square brackets.

What is the right regex for me?

Upvotes: 0

Views: 38

Answers (1)

Cubix48
Cubix48

Reputation: 2681

Here is one way to do so:

\[{1,2}(\[*)|]{1,2}(]*)

var email = Regex.Replace(emailaddress, @"\[{1,2}(\[*)|]{1,2}(]*)", "$1$2");

You can test it here, and here.


  • \[{1,2}: Matches [ between one and two times.
  • (\[*): Matches [ between zero and unlimited times, as much as possible.
  • |: Or.
  • ]{1,2}: Matches ] between one and two times.
  • (]*): Matches ] between zero and unlimited times, as much as possible.

Upvotes: 2

Related Questions