2010-11-20 90 views

回答

3
function TForm1.FindText(const aPatternToFind: String):Boolean; 
    var 
    p: Integer; 
    begin 
    p := pos(aPatternToFind, Memo1.Text); 
    Result := (p > 0); 
    if Result then 
     begin 
     Memo1.SelStart := p; 
     Memo1.SelLength := Length(aPatternToFind); 
     Memo1.SetFocus; // necessary so highlight is visible 
     end; 
    end; 

如果WordWrap爲true,則不會跨行搜索。

+0

在'TStrings.Text'而不是'TStrings.Strings'中搜索非常昂貴。 2×N的事實。 – 2010-11-23 10:49:18

+0

@ user205376 - 你爲什麼這麼說? TStrings.Text是我認爲pos()會快的單個字符串。正如您所建議的,搜索TStrings.Strings將涉及下標以訪問每個字符串。國際海事組織的意見將會更慢,並且不會提供pos()沒有的附加功能。 (而且,它需要一些棘手的代碼來突出顯示所發現的模式)爲什麼你認爲不是? – RobertFrank 2010-11-25 18:27:04

+0

遊戲有點遲,但對於上述情況,則取決於實施情況。所有TStrings都是抽象的。 Memo.Lines.Text(= TMemoStrings.Text)使用單個API調用獲取備忘文本,而TStringList存儲單獨的字符串,TStringList.Text將它們組合爲每個請求中的單個字符串(這通常比調用更快API,順便說一句)。答案使用Memo1.Text,我想繞過任何TStrings後裔,並直接在備忘錄的句柄上調用一些GetText API。 – GolezTrol 2017-08-21 07:40:32

11

此搜索允許文檔換行,大小寫(in)敏感搜索和從光標位置搜索。

type 
    TSearchOption = (soIgnoreCase, soFromStart, soWrap); 
    TSearchOptions = set of TSearchOption; 


function SearchText(
    Control: TCustomEdit; 
    Search: string; 
    SearchOptions: TSearchOptions): Boolean; 
var 
    Text: string; 
    Index: Integer; 
begin 
    if soIgnoreCase in SearchOptions then 
    begin 
    Search := UpperCase(Search); 
    Text := UpperCase(Control.Text); 
    end 
    else 
    Text := Control.Text; 

    Index := 0; 
    if not (soFromStart in SearchOptions) then 
    Index := PosEx(Search, Text, 
     Control.SelStart + Control.SelLength + 1); 

    if (Index = 0) and 
     ((soFromStart in SearchOptions) or 
     (soWrap in SearchOptions)) then 
    Index := PosEx(Search, Text, 1); 

    Result := Index > 0; 
    if Result then 
    begin 
    Control.SelStart := Index - 1; 
    Control.SelLength := Length(Search); 
    end; 
end; 

即使備忘錄未被聚焦,您也可以在備忘錄上設置HideSelection = False來顯示選擇內容。

使用這樣的:

SearchText(Memo1, Edit1.Text, []); 

允許搜索編輯爲好。

+0

使用UpperCase可能不會給你想要的結果,例如在法語中,大寫字母不能有重音,而小寫字符可以有一個(這與加拿大法語不同,我認爲,大寫字母也可以重音)。所以,在這種情況下使用LowerCase會給出更好的結果。 – dummzeuch 2010-11-20 14:40:25

+0

那麼,重音字母和非重音字母是兩個不同的字母,不是嗎?一個法語單詞,當轉換爲UpperCase時,將顯示爲PRIVé,小寫字母表示它是私密的。另一方面,大寫字母é也不會被轉換爲é,所以我不明白這會如何影響搜索結果。儘管我必須承認我在Delphi 7中測試了這個功能。如果在使用LowerCase時unicode或者Delphi中區域設置的可能使用會產生更好的結果,請做。 – GolezTrol 2010-11-20 23:21:03

+2

GolezTrol:感謝HideSelection提示! – RobertFrank 2010-11-21 21:30:10