1
eag = 'linux'
rpat = re.compile("^\s*%s\s*=\s*('.*\'')" % eag)

trying to grab r'^LIN' in a line in a text file, linux = r'^LIN',

lines = [line.strip() for line in open (myfile, 'r')]
for line in lines:
    if re.match(rpat, line)
        matched = re.match(rpat,line)
        got_it = matched.group(1)
        # do something here

Not quite sure if my rpat is correct
There is some space in the front of linux then some space until = then some space r'^LIN',

1
  • Not sure what you are trying to achieve, but when I am debugging regex I like to use this website. gskinner.com/RegExr Commented Aug 28, 2013 at 17:30

3 Answers 3

2

I'd use:

re.compile("^\s*%s\s*=\s*(r'[^']+')" % re.escape(eag))

This matches the r as well, which you omitted.

Demo:

>>> import re
>>> sample = "linux = r'^LIN',"
>>> eag = 'linux'
>>> rpat = re.compile("^\s*%s\s*=\s*(r'[^']+')" % re.escape(eag))
>>> rpat.match(sample).group(1)
"r'^LIN'"
Sign up to request clarification or add additional context in comments.

Comments

1

Your regex is quite messy.

I have tried to fix it:

rpat = re.compile(r"^\s*%s\s*=\s*(r'.*')\s*" % eag)

Your forgot r to match r'LIN' and forgot about trailing spaces.

Comments

0

rpat = re.compile("^\s*%s\s*=\s*(.*\')" % eag) works too. Just had to get rid of ''

Comments

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.