匹配并替换string中的第一个和最后一个字符

时间:2021-08-06 16:52:27

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.

期望的结果:你好%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.

我知道如果案例结合了StartsWith(),EndsWith()等,我可以解决这个问题。但我正在寻找一个更清洁的解决方案。

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

我想regexp就是去这里的方式,而这正是我需要你帮助的地方。

3 个解决方案

#1


13  

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:

但是如果你真的需要一个正则表达式,你需要使用start(^)和end($)锚点,如下所示:

string result = Regex.Replace(input, "^%|%$", "");

#2


5  

s = s.Trim('%');

Regex is not the way to go for simple stuff, but if you insist:

正则表达式不是简单的东西,但如果你坚持:

s = Regex.Replace(s, @"^%+|%+$", "");

#3


1  

You could do the following:

您可以执行以下操作:

 string s = "%hello%world";
 char c = '%';
 int indexBegin = s[0] == c ? 1 : 0;
 int indexEnd = s[s.Length - 1] == c ? 1 : 0;
 s = s.Substring(indexBegin, s.Length - (indexEnd+indexBegin));

#1


13  

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:

但是如果你真的需要一个正则表达式,你需要使用start(^)和end($)锚点,如下所示:

string result = Regex.Replace(input, "^%|%$", "");

#2


5  

s = s.Trim('%');

Regex is not the way to go for simple stuff, but if you insist:

正则表达式不是简单的东西,但如果你坚持:

s = Regex.Replace(s, @"^%+|%+$", "");

#3


1  

You could do the following:

您可以执行以下操作:

 string s = "%hello%world";
 char c = '%';
 int indexBegin = s[0] == c ? 1 : 0;
 int indexEnd = s[s.Length - 1] == c ? 1 : 0;
 s = s.Substring(indexBegin, s.Length - (indexEnd+indexBegin));