Zhu
Zhu

Reputation: 3895

How to remove special characters if it's only at the position of first and last in a string c#

I am trying to remove special characters if it occurs as first and last char of a string .

code ;

  Regex.Replace(searchParams.SearchForText, @"(\s+|@|%|&|'|\(|\)|<|>|#)", "");

But it removes special characters even if it in the middle of the string .

ex : input : $input@text%
     output : input@text

Upvotes: 2

Views: 1118

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626927

You may use

var pattern = @"(?:\s+|[@%&'()<>#])";
var result = Regex.Replace(searchParams.SearchForText, $@"^{pattern}|{pattern}$", "");

See the resulting ^(?:\s+|[@%&'()<>#])|(?:\s+|[@%&'()<>#])$ regex demo.

If you need to remove all of these chars from start and/or end of string use

var result = Regex.Replace(searchParams.SearchForText, @"^[@%&'()<>#\s]+|[@%&'()<>#\s]+$", "");

See this regex demo.

Here, note that all single charalternatives are joined into a single character class for more efficient search. They do not have to be escaped inside a character class, so the pattern is even cleaner.

Next, since \s+ matches one or more whitespace chars, it cannot be merged with single char alternatives in a character class, so a non-capturing group with alternation is used, (?:...|...).

The ^ anchor makes the first ^{pattern} match only at the string start position, and the $ anchor makes the second {pattern}$ alternative match only at the end of string.

Since the pattern should be repeated twice, it is declared as a variable and the regex is built dynamically.

Upvotes: 4

The Snowman
The Snowman

Reputation: 84

You may simply use Trim()

var input = "$input@text%";
var output = input.Trim('@', '%', '$', '\'', '#');

Upvotes: 3

weichch
weichch

Reputation: 10035

var specialChars = "$@%&'()<>#\u0020".ToCharArray();
var trimmed = "$input@text%".Trim(specialChars);

Upvotes: 3

Related Questions