如何从多个备忘录中获取特定字符串

问题描述 投票:-3回答:1

我想检查多个备忘录中的特定字符串,如果所有字符串都检出然后运行一个过程,但在我的代码中,有时程序会运行,有时它不会运行,有时它只在少数人检出时运行。

这是我的代码:

procedure TForm1.Timer14Timer(Sender: TObject);
begin
  if (pos('ActiveTunnel',memo10.Text)<>0) or (pos('https://ipfounder.net/?sponsor',memo10.text)<>0)
    and (pos('ActiveTunnel',memo9.Text)<>0) or (pos('https://ipfounder.net/?sponsor',memo9.text)<>0)
    and (pos('ActiveTunnel',memo8.Text)<>0) or (pos('https://ipfounder.net/?sponsor',memo8.text)<>0)
    and (pos('ActiveTunnel',memo7.Text)<>0) or (pos('https://ipfounder.net/?sponsor',memo7.text)<>0)
    and (pos('ActiveTunnel',memo6.Text)<>0) or (pos('https://ipfounder.net/?sponsor',memo6.text)<>0)
    and (pos('ActiveTunnel',memo5.Text)<>0) or (pos('https://ipfounder.net/?sponsor',memo5.text)<>0)
    and (pos('ActiveTunnel',memo4.Text)<>0) or (pos('https://ipfounder.net/?sponsor',memo4.text)<>0)
    and (pos('ActiveTunnel',memo3.Text)<>0) or (pos('https://ipfounder.net/?sponsor',memo3.text)<>0)
    and (pos('ActiveTunnel',memo2.Text)<>0) or (pos('https://ipfounder.net/?sponsor',memo2.text)<>0)
    and (pos('ActiveTunnel',memo1.Text)<>0) or (pos('https://ipfounder.net/?sponsor',memo1.text)<>0)
  then
  begin
    if Checkbox1.Checked = true then
    begin
      starttun;
      sleep(3000);
      routesaddlast;
    end;
  end;
end;
delphi delphi-7
1个回答
5
投票

如果你看看this table,你会发现and的优先级高于or。这意味着您的代码中的子句实际上相当于:

if (pos(..., memo10.Text) <> 0) 
   or ((pos(..., memo10.Text) <> 0) and (pos(..., memo9.Text) <> 0))
   or ((pos(..., memo9.Text) <> 0) and (pos(..., memo8.Text) <> 0))
   or ((pos(..., memo8.Text) <> 0) and (pos(..., memo7.Text) <> 0))
   etc...

这就是为什么你得到它有时它按预期工作,有时它没有。我猜你真的想要:

if ( (pos(..., memo10.Text) <> 0) or (pos(..., memo10.text) <> 0) ) and
   ( (pos(..., memo9.Text) <> 0) or (pos(..., memo9.text) <> 0) ) and
   ( (pos(..., memo8.Text) <> 0) or (pos(..., memo8.text) <> 0) ) and
   etc...

换句话说,在or-子句周围添加括号,使它们的优先级高于和。

请注意,so you don't have to repeat yourself,您可以这样做:

const 
  S0 = 'ActiveTunnel';
  S1 = 'https://ipfounder.net/?sponsor';

procedure TForm1.Timer14Timer(Sender: TObject);
begin
  if ((Pos(S0, memo10.Text) <> 0) or (Pos(S1, memo10.Text) <> 0)) and
     ((Pos(S0, memo9.Text) <> 0) or (Pos(S1, memo9.Text) <> 0)) and
  // etc...  

并简化这个:

function FindIt(memo: TMemo): Boolean;
begin
  Result := (Pos(S0, memo.Text) <> 0) or (Pos(S1, memo.Text) <> 0);
end;

procedure TForm1.Timer14Timer(Sender: TObject);
begin
  if FindIt(memo10) and 
     FindIt(memo9) and 
     FindIt(memo8) // etc. 

当然,您也可以为FindIt提供一个开放数组参数并传递任意数量的字符串,以使其更通用。

© www.soinside.com 2019 - 2024. All rights reserved.