.net Regex.Replace不排除插入符

时间:2017-05-03 03:32:58

标签: .net regex vb.net regex-negation

我尝试使用.NET Regex.Replace(VB.NET中的示例)从字符串中排除所有非字符和空格。例如,在下面的字符串s中,我认为模式[^ A-z]应该删除除空格之外的所有非字母表。但是,这似乎不起作用。我做错了什么?

Sub Try_Regex_Remove_Caret_Symbol()
' ^ (caret) character is not being removed via exclusion
Dim s As String, p As String
s = "I have a caret which I want removed ^$@#!&"
p = "[^A-z ]"
Console.WriteLine("Input : " & s)
Console.WriteLine("Output: " & Regex.Replace(s, p, ""))
' Input : I have a caret which I want removed ^$@#!&
' Output: I have a caret which I want removed ^
' Note that the caret (^) is not removed as expected
End Sub

2 个答案:

答案 0 :(得分:2)

这是ascii表

    0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F

  2     !  "  #  $  %  &  '  (  )  *  +  ,  -  .  /

  3  0  1  2  3  4  5  6  7  8  9  :  ;  <  =  >  ?

  4  @  A  B  C  D  E  F  G  H  I  J  K  L  M  N  O

  5  P  Q  R  S  T  U  V  W  X  Y  Z  [  \  ]  ^  _

  6  `  a  b  c  d  e  f  g  h  i  j  k  l  m  n  o

  7  p  q  r  s  t  u  v  w  x  y  z  {  |  }  ~  

您会注意到插入符号( ^ )位于A和z之间。为了达到您想要的效果,您需要:

p = [^A-Za-z ]

答案 1 :(得分:0)

使用以下正则表达式进行替换:

[^A-Za-z ]

问题是插入符号位于A-Za-z之间,因此您将其替换为[^A-z]

完整代码:

s = "I have a caret which I want removed ^$@#!&"
p = "[^A-Za-z ]"
Console.WriteLine("Input : " & s)
Console.WriteLine("Output: " & Regex.Replace(s, p, ""))

在这里演示:

Rextester