2013-12-18 41 views
1

所以我有一个整数列表,它们是我希望选择的字内的字符的索引。我的清单是selMid我想要做的是找到索引为单词的第一个字母,然后是最后一个字母,这样我就可以得到长度为的单词。例如,假设我双击一个单词,并仅突出显示单词,这是我希望实现的类似功能。现在我所做的代码有效,但前提是该代码以(开头。我需要它可能与所有特殊字符一起工作。我正在考虑使用正则表达式,但是我在实现它时遇到了问题,我认为我认为会起作用的匹配模式,但我无法弄清楚如何从字符串中的索引位置开始它。查找从字中间的字符串中的字开始

Public loopChar As Char 
Public loopCharIndex As Integer 
Public successBool As Boolean 

Public Function indexSelection() 
     For Each item In selMid 
     Do 
      'Dim pattern As String = "\b" 
      'Dim m As Match = Regex.Match(RichTextBox1.Text.ToString, pattern, RegexOptions.RightToLeft) 
      loopChar = GetChar(RichTextBox1.Text.ToString, item + 1) 
      Console.Write(loopChar) 
      loopCharIndex = item + 1 
      item = item - 1 
     Loop Until (Asc(loopChar) = 40) 
     'If m.Success Then 
     'Console.WriteLine("Found '{0}' at position {1} {2}.", m.Value, m.Index, m.Value.ToString.Count) 
     'successBool = True 
     'End If 
     'Loop Until (successBool) 

     Console.WriteLine(loopCharIndex) 
    Next 
    End Function 

希望我的问题是有道理的,

感谢您帮助

回答

1

你可以做到这一点(我会坦率地承认它可能不是最好的方法),通过查找单词边界向后并使用Regular Expressions在字符串中转发。

尝试这样:

Dim reF As Regex = New Regex("(.*?)\b") 
Dim reB As Regex = New Regex("(.*?)\b", RegexOptions.RightToLeft) 
Dim word as String = String.Empty 

If reB.IsMatch(RichTextBox1.Text, selMid - 1) Then 
    word = reB.Match(RichTextBox1.Text, selMid - 1).Groups(1).Value 
End If 

If reF.IsMatch(RichTextBox1.Text, selMid) Then 
    word &= reF.Match(RichTextBox1.Text, selMid).Groups(1).Value 
End If 

所以,基本上这将启动从一个字符搜索背后的selMid值,由右至左(字符串中向后匹配)看,然后搜索从开始以相反的方式selMid(确保两个搜索不重叠)。以非贪婪的方式将任何字符匹配到单词边界,它应该只找到selMid所在的单词。