I want to get char/word after my keyword. In my code I've got keyword = function. When user writes in richtextbox "function a" I need to get "a" and I can't set in like function because this will be inserted by a user. My code look like this:
string keyword = "function";
string newString = randomString;
TextRange text = new TextRange(_richTextBox.Document.ContentStart, _richTextBox.Document.ContentEnd);
TextPointer current = text.Start.GetInsertionPosition(LogicalDirection.Forward);
while (current != null)
{
string textInRun = current.GetTextInRun(LogicalDirection.Forward);
if (!string.IsNullOrWhiteSpace(textInRun))
{
int index = textInRun.IndexOf(keyword);
if (index != -1)
{
TextPointer selectionStart = current.GetPositionAtOffset(index, LogicalDirection.Forward);
TextPointer selectionEnd = selectionStart.GetPositionAtOffset(keyword.Length, LogicalDirection.Forward);
TextRange selection = new TextRange(selectionStart, selectionEnd);
selection.Text = newString;
selection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
_richTextBox.Selection.Select(selection.Start, selection.End);
_richTextBox.Focus();
}
}
current = current.GetNextContextPosition(LogicalDirection.Forward);
This is a job for Regular Expressions . I highly advise you learn how to use them, as they are incredibly powerful. Here is an example of what you could do:
public void ExecuteCommand (string commandText)
{
var match = Regex.Match(commandText, @"^(\w+)\s*(.*)$");
if (match.Success)
{
string keyword = match.Groups[1].Value;
string parameters = match.Groups[2].Value;
switch (keyword)
{
case "function":
MyFunction(parameters);
break;
default:
throw new NotImplementedException();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.