Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex search for string at beginning of line in file

Here's my code:

#!/usr/bin/python
import io
import re
f = open('/etc/ssh/sshd_config','r')
strings = re.search(r'.*IgnoreR.*', f.read())
print(strings)

That returns data, but I need specific regex matching: e.g.:

^\s*[^#]*IgnoreRhosts\s+yes

If I change my code to simply:

strings = re.search(r'^IgnoreR.*', f.read())

or even

strings = re.search(r'^.*IgnoreR.*', f.read())

I don't get anything back. I need to be able to use real regex's like in perl

like image 433
Glitch Cowboy Avatar asked May 31 '13 16:05

Glitch Cowboy


People also ask

How do you search for a regex pattern at the beginning of a string in Python?

match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object.

How do I find a line starting with Python?

The startswith() string method checks whether a string starts with a particular substring. If the string starts with a specified substring, the startswith() method returns True; otherwise, the function returns False.

Which regex matches the end of line?

End of String or Line: $ The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions. Multiline option, the match can also occur at the end of a line.


1 Answers

You can use the multiline mode then ^ match the beginning of a line:

#!/usr/bin/python
import io
import re
f = open('/etc/ssh/sshd_config','r')

strings = re.search(r"^\s*[^#]*IgnoreRhosts\s+yes", f.read(), flags=re.MULTILINE)
print(strings.group(0))

Note that without this mode you can always replace ^ by \n

Note too that this file is calibrated as a tomato thus:

^IgnoreRhosts\s+yes

is good enough for checking the parameter


EDIT: a better way

with open('/etc/ssh/sshd_config') as f:
    for line in f:
        if line.startswith('IgnoreRhosts yes'):
            print(line)

One more time there is no reason to have leading spaces. However if you want to be sure you can always use lstrip().

like image 138
Casimir et Hippolyte Avatar answered Oct 16 '22 07:10

Casimir et Hippolyte