Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
sorry if this is a stupid question but how do i find a pattern in richtextbox??

the text is like :

hello i want to {help|meet|call} you.

i want to find all such strings which have curly braces and then replace the whole string with any word from within it, RANDOMLY.

so on the click of a button the above line might become :

hello i want to help you.
OR
hello i want to call you.

i thought of using regex but iam completely blank on how to use it, also i didnt understand some tutorials on google.
Posted
Comments
OriginalGriff 1-Aug-10 3:44am    
Change the regex as show in revised answer - '[' and ']' are "match any char in this list" and starting with '^' says "match any character NOT in this list". Your original example din't show two sets of matches in the same line, so I didn't consider that case. Go to www.ultrapico.com and get a copy of Expresso - it helps explain and design regexes. It's free, it really works and I wish I'd written it!

1 solution

You can do it with an advanced Regex - it is the random bit that means you need anything complex:
Random r = new Random();
private void butRegex_Click(object sender, EventArgs e)
    {
    //string stringWithTextIn = "hello i want to {help|meet|call} you.";
    string stringWithTextIn = "hello i want to {help|meet|call} you {please|come|soon}.";
    // Regex regex = new Regex(@"({.*})");
    Regex regex = new Regex(@"({[^}]*})");
    string r = regex.Replace(stringWithTextIn, new MatchEvaluator(ReplaceMatch));
    MessageBox.Show(r);
    }
string ReplaceMatch(Match m)
    {
    string s = m.Value;                     // Get matched text only
    s = s.Substring(1, s.Length - 2);       // Remove '{' and '}'
    string[] parts = s.Split('|');          // Break into words
    return parts[r.Next(0,parts.Length)];   // return randow word
    }

[edit]Changed Regex and test string as shown - new version specifically until closing '}' character[/edit]
 
Share this answer
 
v3
Comments
amit_upadhyay 31-Jul-10 10:09am    
thanks but why does it get weird when i use a string like : "hello i want to {help|meet|call} you {please|come|soon}." i get message as : "hello i want to call} you {please". i guess iam missing something??
amit_upadhyay 1-Aug-10 22:55pm    
Reason for my vote of 5
works perfectly

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