在特定字符之间获取文字



我想在';'之间获得文本特点。但是,如果有3个匹配项,我想在";"之间获得文字。当前光标位置的特征。我正在使用多个文本框。

示例;

select * from database;
----> **Lets say my cursor is here** 
select 
orders from
customer;

select * from employees;

所以,我只想从客户'text。

中选择'

您能分享您对此的想法吗?

要实现这一目标,您首先必须找到所有指示;的指示。为此,遍历所有指示(来源(:

private List<int> AllIndicesOf(string strToSearch, string fullText)
{
    List<int> foundIndices = new List<int>();
    for (int i = fullText.IndexOf(strToSearch); i > -1; i = fullText.IndexOf(strToSearch, i + 1))
    {
        foundIndices.Add(i + 1);
    }
    return foundIndices;
}

然后,您必须将自己的位置与这些索引进行比较,因为您只需要(;的(索引,即光标之后立即跟随:

List<int> indicies = AllIndicesOf(";", txtBxText.Text);
try
{
    if (indicies.Count > 0)
    {           
        int cursorPos = txtBxText.SelectionStart;
        var indicesBefore = indicies.Where(x => x < cursorPos);
        int beginIndex = indicesBefore.Count() > 0 ? indicesBefore.Last() : 0;
        int endIndex = indicies.Where(x => x > beginIndex).First();
        txtBxSelected.Text = txtBxText.Text.Substring(beginIndex, endIndex - beginIndex);
    }
}
catch { }

如果您的光标位置属于所有其他索引,则使用try-catch语句来防止Exception

可以在此处下载示例项目。

此解决方案完美地工作,尽管您需要再次检查它并考虑一些可能的例外。我自己没有考虑他们,因为我认为最好被你处理。我还使用了比多线文本框更好的richTextBox享受代码bro

 private void button1_Click(object sender, EventArgs e)
        {
            var ultimateResult = string.Empty;
            var cusrPosition = richTextBox1.SelectionStart;
            var currentStr = string.Empty;
            var strDic = new Dictionary<string,int>();                
            var textArr = richTextBox1.Text.ToCharArray();
            for (var i = 0; i < textArr.Count(); i++)
            {
                if (textArr[i] != ';')
                    currentStr = currentStr + textArr[i];
                else
                {
                    strDic.Add(currentStr,i);
                    currentStr = string.Empty;
                }
            }
            ultimateResult = strDic.First(item => item.Value >= cusrPosition).Key;
            textBox1.Text = ultimateResult;
        }

最新更新