Как получить символ / текст после моего установленного ключевого слова в richtextbox WPF C # - PullRequest
0 голосов
/ 10 декабря 2018

Я хочу получить символ / слово после моего ключевого слова.В моем коде у меня есть ключевое слово = функция.Когда пользователь пишет в richtextbox «function a», мне нужно получить «a», и я не могу установить подобную функцию, потому что она будет вставлена ​​пользователем.Мой код выглядит так:

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);

1 Ответ

0 голосов
/ 10 декабря 2018

Это работа для Регулярных выражений .Я настоятельно советую вам научиться пользоваться ими, поскольку они невероятно мощные.Вот пример того, что вы могли бы сделать:

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();
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...