首页 > 解决方案 > How to get specific strings from multiple memos

问题描述

I want to check specific strings from multiple memos and if all of them check out then run a procedure, but in my code sometimes the procedure runs and sometimes it doesn't, and sometimes it runs only when a few have checked out.

Here is my code:

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;

标签: delphidelphi-7

解决方案


如果您查看此表,您会发现它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 子句周围添加括号以赋予它们比and更高的优先级。

请注意,因此您不必重复自己,您可以这样做:

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一个开放数组参数并传递任意数量的字符串,以使其更通用。


推荐阅读