Determine if string exists in file

2019-03-04 04:56发布

问题:

I have a list of strings such as:

John

John Doe

Peter Pan

in a .txt file.

I want to make a loop that checks if a certain name exists. However, I do not want it to be true if I search for "Peter" and only "Peter Pan" exists. Each line has to be a full match.

回答1:

Ha ha, ep0's answer is very sophisticated!

However, you want to use a parsing loop something like this (this example expects that your names are separated by carriage returns). Consider that you have a text file with contents arranged like this:

John
Harry
Bob
Joe

Here is your script:

fileread, thistext, %whatfile%  ;get the text from the file into a variable
;Now, loop through each line and see if it matches your results:

loop, parse, thistext, `r`n, `r`n
{
  if(a_loopfield = "John")
     msgbox, Hey! It's John!
  else
     msgbox, No, it's %a_loopfield%
}

If your names are arranged in a different order, you might have to either change the delimiter for the parsing loop, or use regex instead of just a simple comparison.



回答2:

If you want to check for multiple names use a trie. If you have just one name, you can use KMP.

I'll explain this for multiple names you want to check that exist, since for only one, the example provided on Wikipedia is more than sufficient and you can apply the same idea.

Construct the said trie from your names you want to find, and for each line in file, traverse the trie character by character until you hit a final node.

BONUS: trie is used by Aho-Corasick algorithm, which is an extension of KMP to multiple patters. Read about it. It's very worthwhile.

UPDATE:

For checking if a single name exists, hash the name you want to find, then read the text file line by line. For each line, hash it with the same function and compare it to the one you want to find. If they are equal, compare the strings character by character. You need to do this to avoid false positives (see hash collisions)



标签: autohotkey