3

I want to replace every line in a textfile with " " which starts with "meshname = " and ends with any letter/number and underscore combination. I used regex's in CS but I never really understood the different notations in Python. Can you help me with that?

Is this the right regex for my problem and how would i transform that into a Python regex?

m.e.s.h.n.a.m.e.' '.=.' '.{{_}*,{0,...,9}*,{a,...,z}*,{A,...,Z}*}*

x.y = Concatenation of x and y  
' ' = whitespace  
{x} = set containing x  
x* = x.x.x. ... .x or empty word

What would the script look like in order to replace every string/line in a file containing meshname = ... with the Python regex? Something like this?

fin = open("test.txt", 'r')
data = fin.read()
data = data.replace("^meshname = [[a-z]*[A-Z]*[0-9]*[_]*]+", "")
fin.close()
fin = open("test.txt", 'w')
fin.write(data)
fin.close()

or is this completely wrong? I've tried to get it working with this approach, but somehow it never matched the right string: How to input a regex in string.replace?

Doesbaddel
  • 214
  • 3
  • 17

1 Answers1

1

Following the current code logic, you can use

data = re.sub(r'^meshname = .*\w$', ' ', data, flags=re.M)

The re.sub will replace with a space any line that matches

  • ^ - line start (note the flags=re.M argument that makes sure the multiline mode is on)
  • meshname - a meshname word
  • = - a = string
  • .* - any zero or more chars other than line break chars as many as possible
  • \w - a letter/digit/_
  • $ - line end.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563