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
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.
var specialChars = "$@%&'()<>#\u0020".ToCharArray();
var trimmed = "$input@text%".Trim(specialChars);
You may simply use Trim()
var input = "$input@text%";
var output = input.Trim('@', '%', '$', '\'', '#');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.