Click here to Skip to main content
15,891,895 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i have this text "<set> <value> <name>" in a file, now i need to remove the character "<" and ">" which is in between the text. im trying with the below code

C#
private void button1_Click(object sender, EventArgs e)
{
sr = new StreamReader(sam);
 textBox1.Text = sr.ReadLine();
string pattern = "\"(?=[<\"]+,)[>\"]+\"";
                string result = Regex.Replace(textBox1.Text, pattern, m => m.Value.Replace("<", " "));
                textBox2.Text = result;
sr.Close();
}

im confused with this regular expression and im getting the same output
"<set> <value> <name>"
please help....
Posted
Updated 24-Mar-12 3:39am
v2

Try the below code:

C#
string pattern = "\"([^\"]+)\"";
value = Regex.Match(textToSearch, pattern).Value;

string[] removalCharacters = {"\""}; //or any other characters
foreach (string character in removalCharacters)
{
    value = value.Replace(character, "");
}
 
Share this answer
 
We're only removing two characters, and we know which two they are. Using Regex seems a bit like overkill in this case. If you were removing a large variation of characters, then I would do a scan to create an index-map of which characters to remove, convert the string into an array, and use a for loop the skips any index in that map (most likely a HashSet<int>) to insert the character's into a string builder to avoid a O(n^2) situation. Yet, if this is only place where you're stripping out characters, then the following code is just fine.

private void button1_Click(object sender, EventArgs e)
{
    string s;

    try
    {
        using (StreamReader sr = new StreamReader(sam))
        {
            s = sr.ReadLine();
        }
    }
    catch
    {
        s = null;
    }

    textBox1.Text = s;

    if(s != null)
    {
        s = s.Replace("<", string.Empty);
        s = s.Replace(">", string.Empty);
    }

    textBox2.Text = s;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900