2007. április 18., szerda
Find whole words within a string
Problem/Question/Abstract:
Does anyone know of a function that finds a whole word within a string as in the search and replace options?
Answer:
{Function FindWord
Parameters:
pattern: word to search for
text: text to search
caseSensitive: determines whether search is case sensitive or not. Default is not case-sensitive.
startAt: first character to search, default is 1.
Returns:
The start of the first instance of the word, or 0, if the word was not found or only as part of larger words. A word in this context is any sequence of alphanumeric characters delimited by non-alphanumeric characters.
Error Conditions: none
Created: 18.05.99 by P. Below}
function FindWord(pattern, text: string; caseSensitive: Boolean = false; startAt:
Integer = 1): Integer;
var
offset, endOfPattern: Integer;
begin
Result := 0;
if Length(text) = 0 then
exit;
if Length(pattern) = 0 then
begin
{By definition a pattern of length 0 is always found}
result := 1;
Exit;
end;
if not caseSensitive then
begin
pattern := AnsiLowerCase(pattern);
text := AnsiLowerCase(text);
end;
endOfPattern := startAt + Length(pattern);
for offset := startAt to Length(text) - Length(pattern) + 1 do
begin
if pattern[1] = text[offset] then
begin
if ((offset = 1) or not IsCharAlphaNumeric(text[offset - 1])) and ((endOfPattern
> Length(text)) or not IsCharAlphaNumeric(text[endOfPattern]))
and (StrLComp(@text[offset], @pattern[1], Length(pattern)) = 0) then
begin
Result := offset;
exit;
end;
end;
Inc(endOfPattern);
end;
end;
Feliratkozás:
Megjegyzések küldése (Atom)
Nincsenek megjegyzések:
Megjegyzés küldése