如何从string中去除非字母数字字符(包括空格)?
如何从string中去除非字母数字字符并在C#中用Replacereplace空格?
我想保持az,AZ,0-9,没有什么更多(甚至没有“空格”)。
"Hello there(hello#)".Replace(regex-i-want, ""); 应该给
 "Hellotherehello" 
  "Hello there(hello#)".Replace(@"[^A-Za-z0-9 ]", "");我试过了"Hello there(hello#)".Replace(@"[^A-Za-z0-9 ]", ""); 但空间仍然存在。 
 在你的正则expression式中,你已经排除了匹配的空格(你还没有使用过我完全忽略的Regex.Replace() ): 
 result = Regex.Replace("Hello there(hello#)", @"[^A-Za-z0-9]+", ""); 
 应该pipe用。  +通过一次匹配多个连续的非字母数字字符而不是一个一个来使正则expression式更有效。 
如果您还想保留非ASCII字母/数字,请使用以下正则expression式:
 @"[^\p{L}\p{N}]+" 
离开
 BonjourmesélèvesGutenMorgenliebeSchüler 
代替
 BonjourmeslvesGutenMorgenliebeSchler 
您可以使用Linq过滤出所需的字符:
  String source = "Hello there(hello#)"; // "Hellotherehello" String result = new String(source .Where(ch => Char.IsLetterOrDigit(ch)) .ToArray()); 
要么
  String result = String.Concat(source .Where(ch => Char.IsLetterOrDigit(ch))); 
所以你不需要正则expression式 。
或者你也可以这样做:
  public static string RemoveNonAlphanumeric(string text) { StringBuilder sb = new StringBuilder(text.Length); for (int i = 0; i < text.Length; i++) { char c = text[i]; if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') sb.Append(text[i]); } return sb.ToString(); } 
用法:
 string text = SomeClass.RemoveNonAlphanumeric("text LaLa (lol) á ñ $ 123 ٠١٢٣٤"); //text: textLaLalol123 
上面的错误是使用replace不正确(它不需要正则expression式,感谢CodeInChaos)。
下面的代码应该做什么指定:
 Regex reg = new Regex(@"[^\p{L}\p{N}]+");//Thanks to Tim Pietzcker for regex string regexed = reg.Replace("Hello there(hello#)", ""); 
这给了:
 regexed = "Hellotherehello" 
作为一种扩展方法的替代操作:
 public static class StringExtensions { public static string ReplaceNonAlphanumeric(this string text, char replaceChar) { StringBuilder result = new StringBuilder(text.Length); foreach(char c in text) { if(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') result.Append(c); else result.Append(replaceChar); } return result.ToString(); } } 
并testing:
 [TestFixture] public sealed class StringExtensionsTests { [Test] public void Test() { Assert.AreEqual("text_LaLa__lol________123______", "text LaLa (lol) á ñ $ 123 ٠١٢٣٤".ReplaceNonAlphanumeric('_')); } } 
 var text = "Hello there(hello#)"; var rgx = new Regex("[^a-zA-Z0-9]"); text = rgx.Replace(text, string.Empty); 
使用以下正则expression式使用Regex.Replace去除string中的所有字符
 ([^A-Za-z0-9\s]) 
在.NET 4.0中,您可以使用String类的IsNullOrWhitespace方法来删除所谓的空格字符。 请看这里http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx然而,@CodeInChaos指出,有很多字符可以被视为字母和数字。; 如果您只想查找A-Za-z0-9,则可以使用正则expression式。