1
votes

I am trying to match/sub the following line

line1 = '# Some text\n'

But avoid match/sub lines like this

'# Some text { .blah}\n'

So in other a # followed by any amount of words spaces and numbers (no punctuation) and then the end of line.

line2 = re.sub(r'# (\P+)$', r'# \1 { .text}', line1)

Puts the contents of line1 into line2 unchanged. (I read somewhere that \P means everything except punctuation)

line2 = re.sub(r'# (\w*\d*\s*)+$', r'# \1 { .text}', line1)

Whereas the above gives

'#  { .text}'

Any help is appreciated Thanks Tom

2
What is line1 in line2 = re.sub(r'# (\P+)$', r'# \1 { .text}', line1)? - thefourtheye

2 Answers

1
votes

Your regex is a bit weird; expanded, it looks like

r"# ([a-zA-Z0-9_]*[0-9]*[ \t\n\r\f\v]*)+$"

Things to note:

  1. It is not anchored to the beginning of the string, meaning it would match

    print("Important stuff!")  # Very important
    
  2. The \d* is redundant, because it is already captured by \w*

  3. Looking at your example, it seems you should be less worried about punctuation; the only thing you cannot have is a curly-brace ({).

Try

from functools import partial

def add_text(txt):
    return re.sub(r"^#([^{]*)$", r"#\1 { .text }", txt, flags=re.M)

text = "# Some text\n# More text { .blah}\nprint('abc') # but not me!\n# And once again"

print("===before===")
print(text)
print("\n===after===")
print(add_text(text))

which gives

===before===
# Some text
# More text { .blah}
print('abc') # but not me!
# And once again

===after===
# Some text { .text }
# More text { .blah}
print('abc') # but not me!
# And once again { .text }
-1
votes

If you only want lines which start with a # and continue with alphanumeric values, spaces and _, you want this:

/^#[\w ]+$/gm