Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match and replace first and last character in string

Tags:

c#

regex

asp.net

I would like to remove % characters from the start and the end of a string. For example:

string s = "%hello%world%";

Desired result: hello%world.

I know that I can fix this with some if cases combined with StartsWith(), EndsWith() etc. But I'm looking for a cleaner solution.

I suppose regexp is the way to go here, and that's where I need your help.

like image 994
Johan Avatar asked Nov 29 '22 01:11

Johan


1 Answers

There's no need for a regular expression. Just use this:

string result = input.Trim('%');

But if you really need a regular expression, you'd need to use start (^) and end ($) anchors, like this:

string result = Regex.Replace(input, "^%|%$", "");
like image 109
p.s.w.g Avatar answered Dec 06 '22 10:12

p.s.w.g