简体   繁体   English

使用Delphi在另一个字符串中查找变量字符串

[英]Find a variable string in another string using Delphi

Given a field/string like 'G,H,1,AA,T,AAA,1,E,A,H,....'. 给定类似'G,H,1,AA,T,AAA,1,E,A,H,....'的字段/字符串。 The characters can be in any combination/order. 字符可以是任何组合/顺​​序。 How do I search that string and return True when searching for just 'A' or 'AA'? 如何仅搜索“ A”或“ AA”时搜索该字符串并返回True? ie If doing a search for say 'A', it should only find the 'A' between the E & H. Regards & TIA, Ian 例如,如果搜索说“ A”,则只能在E&H之间找到“ A”。Regards&TIA,Ian

Split this string into a list, for example with TStringList.CommaText (alternatively, into an array with StrUtils.SplitString() ). 将该字符串拆分为一个列表,例如,使用TStringList.CommaText (或者使用StrUtils.SplitString()为一个数组)。

Then, just walk through the list and check every string (or use TStrings.IndexOf() - note: it uses CaseSensitive property, as Remy mentioned in comments). 然后,只需遍历列表并检查每个字符串(或使用TStrings.IndexOf() -注意:它使用CaseSensitive属性,正如Remy在评论中提到的那样)。

If you are going to make many queries for the same list - sort it and use an effective binary search ( TStringList.Find() ). 如果要对同一列表进行很多查询,请对其进行排序,然后使用有效的二进制搜索( TStringList.Find() )。

You can simply split your string into an array by your delimiter and search in that array, eg 您可以通过定界符将字符串简单地拆分为一个数组,然后在该数组中进行搜索,例如

function FindItem(const List, Item: string): Boolean;
var
  SArr: TArray<string>;
  S: string;
begin
  Result := False;
  //Separators could also be a parameter
  SArr := List.Split([',']);
  for S in SArr do
  begin
    //use S.Trim if needed
    //use AnsiSameText(S, Item) for case insensitive check
    if Item = S then
      Exit(True);
  end;
end;

If you need to search for multiple items in your data, you might want to sort the array and use a binary search. 如果您需要搜索数据中的多个项目,则可能需要对数组进行排序并使用二进制搜索。

TArray.Sort<string>(SArr);
Result := TArray.BinarySearch(SArr, Item, Tmp);

Another approach would be using regular expressions with word boundaries to search for whole words only 另一种方法是使用带有单词边界的正则表达式仅搜索整个单词

Result := TRegex.IsMatch(List, '\bA\b');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM