BraveVN
BraveVN

Reputation: 430

How to replace the text between 2 characters?

I want to remove the content between 2 characters in a text with Visual C#.
Here is an example:

Given: Hi [everybody], I'm 22 years old, I'm a student [at a University of Technology] in Vietnam
Result: Hi, I'm 22 years old, I'm a student in Vietnam

I use this syntax

string input = "Hi [everybody], I'm 22 years old, I'm a student [at a University of Technology]";
string regex = "(\\[.*\\])";
string output = Regex.Replace(input, regex, "");

but the code is remove all between the first and the last square brackets, so this is the result:

Hi in Vietnam

How can I fix it ?

Upvotes: 0

Views: 2693

Answers (3)

Andie2302
Andie2302

Reputation: 4897

To match the text to replace use:

\s+\[.*?]

As C# String this is:

@"\s+\[.*?]"

If you use @ in front of the string you don't need to escape it in C#.

Upvotes: 0

Rawling
Rawling

Reputation: 50144

.* is greedy, so your expression matches as many characters as possible between a [ and a ] - including many other [s and ]s..

You can fix this one of two ways:

  • Add a ?. which makes the * not greedy: .*? will match as few characters as it can before matching the ].

  • Replace the . with [^]], which will only let the expression match non-] characters inbetween the [ and the ].

Upvotes: 5

Braj
Braj

Reputation: 46861

Just replace everything between [...] with empty string

\s+\[[^\]]*\]

Here is online demo

OR use Non-greedy way but read first ✽ Want to Be Lazy? Think Twice.

\s+\[(.*?)\]

Here is demo

Upvotes: 1

Related Questions