1

How do I remove a character from specific character to specific character ...

Example

 string a = " Hello ! {ssd} jksssss"; 

In above string i want to remove character from '{' to '}'

 output -- > `Hello ! jksssss` 
0

4 Answers 4

5

This can be done with Regex.Replace:

string a = " Hello ! {ssd} jksssss"; string b = Regex.Replace(a, "{\w+}", ""); 

This won't work for "Hi {!#$#@}!", that is left as an excericse :-) Start at this MSDN page for more basic information on regular expressions in .NET.

Sign up to request clarification or add additional context in comments.

3 Comments

Remember to add "using System.Text.RegularExpressions;" at the start of your code for this to work.
abc = Regex.Replace(abc, "{\w+}", ""); // error :Unrecognized escape sequence
Yup. Try @"{\w+}" (with the at symbol). That will treat the backslash as a normal character.
4

One way without using regexp is below:

string a = " Hello ! {ssd} jksssss"; int start = a.IndexOf('{'); int end = a.IndexOf('}', start); if (end > start && start != -1) { a = a.Remove(pos, end-start+1); } 

Comments

3

You can use the Regex class in System.Text.RegularExpressions, to do the replace. For example:

var a = " Hello ! {ssd} jksssss"; var newString = Regex myRegex = new Regex("{{.+}}", ""); myRegex.Replace(a, ""); 

EDIT:

If you want to match multiple occurrances of curly braces, and replace each one, use this regular expression instead:

var a = "Hello ! {ssd} jksssss {tasdas}"; Regex myRegex = new Regex("{{[^{]+}}", ""); var newString = myRegex.Replace(a, ""); // a == "Hello ! jksssss " 

Comments

0

You can also use Regex.Replace(), if you don´t want to find the specific positions and the content between braces varies.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.