0

I am unable to replace a particular occurrence of a certain pattern with edited text. I have used a for...loop to come up with how to get a specific occurrence of the pattern but I am unable to use that with an re.sub statement.

This is my Python 2 code:

def split(content):
    count = 0
    s = ""
    for i in re.finditer(r'(?s)(\\thinhline\n\\\\\[-16pt]\n)([a-zA-Z\s\(\)]+)(.*?)(\n *\\\\)', content):
        count= count + 1
        x =  len(re.findall('^\s*&', i.group(3), re.M))
        if x < 6:
            break
        elif x >= 6:
            g = normalizationConstraints(i.group(3),i.group(2)) + "\n"
            s = str(g) + "\n"
            content = re.sub(i,s,content)
    return content

The error is on the line:

         content = re.sub(i,s,content)

Since the variable "i" is apparently not regex.

The error:

TypeError: first argument must be string or compiled pattern

How can I fix this problem??

Thanks.

3
  • Can you add the actual error message? Commented Mar 20, 2015 at 21:05
  • 1
    what do you think i is? have you tried printing i? Commented Mar 20, 2015 at 21:17
  • 1
    That's a lot of backslashes in your regex. Are you sure it's correct? Can you provide an example of what you intend to achieve with this code? Commented Mar 20, 2015 at 21:22

1 Answer 1

1

I'm not exactly sure what you want, but the error is telling you the right thing: i isn't a regex pattern. re.finditer returns an iterator of MatchObjects, probably strings in this context. re.sub expects a regular expression pattern as its first argument.

Depending on what you're trying to achieve with this code, you either need to use a different function than re.sub, or you need to supply an actual regex. If you can give more details about your goals (maybe the expected output based on some sample input, as @200_success suggests), that would help.

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.