1

I would like to create regular expression using re module. But it's unclear how to create a pattern in the similar way of creating a formatted string, e.g.: I need something like

myPattern = r'\s*{linehead}'.format(someText)

Is this possible?

When I use

if myPattern.search(l) is not None:,

I'm getting

AttributeError: 'str' object has no attribute 'search'

3
  • 1
    Yes, but you need to use a keyword argument for this pattern: myPattern = r'\s*{linehead}'.format(linehead="someText") Commented Mar 14, 2015 at 19:18
  • When I use if myPattern.search(l) is not None:, I'm getting AttributeError: 'str' object has no attribute 'search' Commented Mar 14, 2015 at 19:26
  • 2
    or myPattern = re.compile(r'\s*{linehead}'.format(linehead="someText"); myPattern.search(l) is not None Commented Mar 14, 2015 at 19:31

1 Answer 1

2

As was mentioned in the comments, myPattern is simply a string. The 'r' simply tells Python that it's a "raw" string and shouldn't attempt to interpret escaped text.

Once you have your regular expression formatted the way you like it (note, since you named the parameter "linhead", you'll need to identify it in the arguments to format:

myPattern = r'\s*{linehead}'.format(linehead="someText")

You need to make an regular expression object with re.compile().

myRegex = re.compile(myPattern)

You can now use myRegex as you originally intended:

if myRegex.search(l) is not None:
    ...

Or, you can do this all in one go as @IceArdor suggested:

myPattern = re.compile(r'\s*{linehead}'.format(linehead="someText");

See https://docs.python.org/2/library/re.html#module-re

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

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.