Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex + Python - Remove all lines beginning with a *

Tags:

python

regex

I want to remove all lines from a given file that begin with a *. So for example, the following:

* This needs to be gone
But this line should stay
*remove 
* this too
End

Should generate this:

But this line should stay
End

What I ultimately need to do is the following:

  1. Remove all text inside parenthesis and brackets (parenthesis/brackets included),
  2. As mentioned above, remove lines starting with ''.

So far I was able to address #1 with the following: re.sub(r'[.?]|(.*?)', '', fileString). I tried several things for #2 but always end up removing things I don't want to


Solution 1 (no regex)

>>> f = open('path/to/file.txt', 'r')
>>> [n for n in f.readlines() if not n.startswith('*')]

Solution 2 (regex)

>>> s = re.sub(r'(?m)^\*.*\n?', '', s)

Thanks everyone for the help.

like image 648
Everaldo Aguiar Avatar asked Aug 09 '26 16:08

Everaldo Aguiar


2 Answers

Using regex >>

s = re.sub(r'(?m)^\*.*\n?', '', s) 

Check this demo.

like image 118
Ωmega Avatar answered Aug 12 '26 10:08

Ωmega


You don't need regex for this.

text = file.split('\n') # split everything into lines.

for line in text:
    # do something here

Let us know if you need any more help.

like image 41
kreativitea Avatar answered Aug 12 '26 10:08

kreativitea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!