Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 正则表达式替换特殊字符_C#_Regex - Fatal编程技术网

C# 正则表达式替换特殊字符

C# 正则表达式替换特殊字符,c#,regex,C#,Regex,我的正则表达式需要帮助 我需要删除文本开头的特殊字符 例如,我有一个这样的文本 .just a $#text this should not be incl#uded just a text this should not be incl#uded 输出应该是这样的 .just a $#text this should not be incl#uded just a text this should not be incl#uded ([\!-\/\;-\@]+)[\w\d]+ 如何

我的正则表达式需要帮助

我需要删除文本开头的特殊字符

例如,我有一个这样的文本

.just a $#text this should not be incl#uded
just a text this should not be incl#uded
输出应该是这样的

.just a $#text this should not be incl#uded
just a text this should not be incl#uded

([\!-\/\;-\@]+)[\w\d]+
如何限制正则表达式只检查以特殊字符开头的文本

谢谢

使用前瞻:


(^[.$#]+|)(?以下是您的问题详细信息中的两个可能选项。希望对您有所帮助

string input = ".just a $#text this should not be incl#uded";

//REMOVING ALL THE SPECIAL CHARACTERS FROM THE WHOLE STRING    
string output1 = Regex.Replace(input, @"[^0-9a-zA-Z\ ]+", "");

// REMOVE LEADING SPECIAL CHARACTERS FROM EACH WORD IN THE STRING. WILL KEEP OTHER SPECIAL CHARACTERS     
var split = input.Split();
string output2 = string.Join(" ",  split.Select(s=> Regex.Replace(s, @"^[^0-9a-zA-Z]+", "")).ToArray());

负前瞻在这里是可以的:

(?![\.\$#].*)[\S]+

[\S]
匹配任何字符


(?![\.\$\\\\\\\$\\]..*)
负先行表示那些字符
[\S]+
不应以任何
\.\$\\\\.\$\\\\\\\$\\\\\\\\$\\\\\\$\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

var result = Regex.Replace(s, @"\B[!-/;-@]+\s*\b", "");

详细信息

  • \B
    -单词边界以外的位置(当前位置左侧必须有字符串开头或非单词字符)
  • [!-/;-@]+
    -1个或多个ASCII标点符号
  • \s*
    -0+空格字符
  • \b
    -单词边界,当前位置右侧必须紧靠字母/数字/下划线
如果要删除所有标点符号,请使用

var result = Regex.Replace(s, @"\B[\p{P}\p{S}]+\s*\b", "");


请注意,
\p{p}
匹配任何标点符号,
\p{S}
匹配任何符号。

尝试以下操作:
^([\!-\/\;-\@]+)
这就是你想要的吗?您好@Isaac,它还应该包括$#文本您想删除所有特殊字符还是只删除其中一些字符?您提出的问题细节令人困惑。它是否始终是您只想删除的第一个字符?看,它似乎涵盖了所有情况。感谢您提供了具有详细解释的良好解决方案关于它是如何工作的。