1

I have the following in my python script..

hostIP = sys.argv[1]
hostsFileLoc = "hosts.txt"

if not hostIP in open(hostsFileLoc).read():
    # Script to add if the string is not in file
else:
    # Print message

The only problem with this is that it is not an exact match, for example...

If my file contains:

192.168.0.111

And my hostIP is:

192.168.0.11

Then it will find it as a match. I thought I might be able to do this with regex, as there will always be a space ("\s+") or a comma ("\,") so I thought I could use something like

test = re.compile("^" + hostIP + "[\s\,]*")

and use test as my search, but this obviously does not work. I've tried to find some documentation on this but to no avail. Has anyone a suggestion on how I can use a variable with regex to have a more specific search.

Thanks

MHibbin

2 Answers 2

3

you can split your text file by delimiters (whitespace for example) and then find string in the list:

if not hostIP in open(hostsFileLoc).read().split():
    # Script to add if the string is not in file
else:
    # Print message

Put your delimiter into split() if you use other than whitespaces

Sign up to request clarification or add additional context in comments.

Comments

3

The only reason it doesn't work is that you use * in "[\s\,]*", which means "space or comma zero or more times". Thus it will match against '192.168.0.111' because it has zero spaces after 11. Change * to + ("one or more times") and it should work.

1 Comment

Thanks, for some reason I thought "+" would mean that it would need at least one whitespace AND one comma... wasn't thinking correctly. However I have gone withe split method in the other answer as that was posted first and it worked for my needs. I will bare this in mind though, thanks for the response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.