Avatar of pingeyeg
pingeyeg
 asked on

Remove last occurrence of characters

I am trying to figure out how to remove the last occurrence of a string of characters at the bottom of a file.  I've got the following script, but it's not doing as requested.  Any ideas would be greatly appreciated.

iter = r"(\*)+"
found = re.findall(iter, finalOutput)[-1]
finalOutput.replace(found, "")

Open in new window


The code I'm running this on is:

*******************************
text
*******************************
<code>

*******************************
text
*******************************
<code>

*******************************
text
*******************************
<code>

*******************************  <-- this line

I want to remove only the last set of *'s.
Regular ExpressionsPython

Avatar of undefined
Last Comment
pingeyeg

8/22/2022 - Mon
Terry Woods

Try this, assuming you can operate on the string as a single value:

mypattern = r"\*+\s*$"
mystring = mystring.replace(mypattern, "")

Open in new window


I also allowed for space characters after the last * characters, just in case there are some.
gelonida

Could you please clarify:

You  have a huge string spanning multiple lines.

You want to find the last occurence of one or more stars and replace them with nothing?

Do these stars have to be in a separate line?
could there be whitespace before or after these stars?
could there still be some text / code after these stars??
ASKER CERTIFIED SOLUTION
kaufmed

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
gelonida

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
pingeyeg

ASKER
TerryAtOpus: Unfortunately, that still leaves the last bit of *'s at the bottom.

gelonida: No space or new lines after the *'s at the bottom.  There are new lines before the *'s.  No text after the *'s either.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
pingeyeg

ASKER
Thanks guys!