Reputation: 23
I need a few lines of code to remove all exclamation marks ("!") starting from the end of the sentence. The code should achieve the following:
"Hi!" --> "Hi"
"Hi!!!" --> "Hi"
"!Hi") --> "!Hi"
"Hi! Hi!") --> "Hi! Hi"
I've tried using RegEx (negative lookahead), however, to no success:
/(?!^)!/g
A short explanation of the solution would be greatly appreciated. Thanks!
Upvotes: 2
Views: 6267
Reputation: 1
def remove(s):
return s[:-1] if s.endswith('!') else s
It should be good
Upvotes: -1
Reputation: 638
I am giving you the solution which i have implemented in the javascript. I don't know which language you are using but anyways logic remains the same.
var text = "!Hi! Hi!!";
var i=text.length - 1;
while(text[i] == "!"){
i--;
}
finalText = text.substring(0,i+1);
console.log(finalText);
Output: !Hi! Hi
You can use same logic to implement in the programming language you are using. If you want to use Regex then the solution mentioned by @Barmar above will work perfectly!
Upvotes: 0
Reputation: 781954
You don't need lookahead. Just match the exclamation points at the end and replace them with an empty string. In PHP this is:
$string = preg_replace('/!+$/', '', $string);
Upvotes: 2
Reputation: 80649
You should use the $
anchor, which marks the end of a string:
/!+$/gm
The m
flag is there in case you have a multiline string.
Upvotes: 2