在Delphi中使用通配符搜索字符串中的模式?

use*_*ser 6 delphi pattern-matching delphi-xe

我曾经使用HYPERSTR库进行字符串处理例程.现在我使用更新的Delphi.我需要在字符串中搜索模式,例如旧函数function IsMatchEx(const Source, Search:AnsiString; var Start:integer) : Integer;.实际上我不需要结果值,我只想知道模式是否与字符串匹配.

我的旧代码(返回TRUE):

var
  StartPos: integer;
  FoundPos: integer;
begin
  StartPos := 1;
  FoundPos := IsMatchEx('abcdef', 'abcd?f', StartPos);
  if FoundPos > 0 then
    showmessage('match');
end;
Run Code Online (Sandbox Code Playgroud)

我看到Delphi XE有TRegEx但我仍然不明白使用它.

这些代码不返回TRUE:

  if TRegEx.IsMatch('abcdef', 'abcd?f') then
    showmessage('match');
Run Code Online (Sandbox Code Playgroud)

使用时我也得到了相同的结果MatchesMask.

谢谢.

小智 9

正则表达式语法不同.?和*有不同的含义.有关正则表达式的精彩介绍,请参见http://www.regular-expressions.info/tutorial.html.您可以使用类似abcd [az] f或abcd\wf的内容,甚至是其他语法,具体取决于您想要匹配的内容.


MGH*_*MGH 6

如果?代表一个字符:

  if TRegEx.IsMatch('abcdef', 'abcd.f') then
    showmessage('match');
Run Code Online (Sandbox Code Playgroud)

如果?代表任何刺痛:

  if TRegEx.IsMatch('abcdef', 'abcd.*f') then
    showmessage('match');
Run Code Online (Sandbox Code Playgroud)

没有XE所以没有测试过.