在richtextbox中找到一个字符串模式 [英] find a string pattern in richtextbox
问题描述
很抱歉,如果这是一个愚蠢的问题,但是如何在Richtextbox中找到模式?
文字是这样的:
你好,我想{help | meet |给}打电话.
我想找到所有带有花括号的字符串,然后将整个字符串替换为RANDOMLY中的任何单词.
因此,单击按钮,上面的行可能变为:
你好,我想帮助你.
或
你好,我想打电话给你.
我曾考虑过使用正则表达式,但在使用方法上完全空白,我也不了解google上的一些教程.
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.
推荐答案
您可以使用高级正则表达式-它是随机的,这意味着您需要任何复杂的东西:
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]更改了正则表达式和测试字符串,如下所示-特别是新版本,直到关闭}"字符为止[/edit]
[edit]Changed Regex and test string as shown - new version specifically until closing ''}'' character[/edit]
这篇关于在richtextbox中找到一个字符串模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!