2013-12-18 49 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所在的單詞。