开发者

Regular Expression confusion

I want to check a name using regular expression, but I'm not getting convincing result. Could anyone please suggest what wrong I'm doing in my regular expression pattern?

开发者_如何转开发foreach(Match m in
(Regex.Matches("Jack_Sparrow","^[A-za-z]+[^-]*(\\d)*$")))
     { 
      Console.WriteLine("{0} found at index{1}",m.Value,m.Index);
     }

May I know why I'm getting Jack_Sparrow as output, despite of not checking underscore(_) in the patter? I rather want Jack Sparrow as an output. What's modification I need?


The first half of your character range is including it.

[A-za-z] creates a range from upper case A to lower case z, then another range from lower case a to lower case z. These ranges overlap in their second portion because of the way the ASCII values work out. Specifically, A-z creates a range from ASCII character 65 (A) to character 122 (z). The underscore character has a value of 95, which is in between. Since your regex is anchored, this character class is where the match is occurring. I've changed your character class to include grouping parentheses in this example so that you can see it is capturing the entire text of "Jack_Sparrow".

You should be able to solve this specific match by changing the character range to be [A-Za-z] instead. It will, however, still match the first portion ("Jack") and then the [^-]* portion will match the remainder of the string ("_Sparrow"), still causing it to be a valid match. If you can provide some other text examples, then we can help you refine this further, though. With the current information you've provided, it's difficult to tell how to best fix the [^-] issue.


[^-] checks for any character other than -, so that's what matches the underscore. I'm not sure exactly what you want to match here.

Are you trying to change everything other than letters to spaces, perhaps?


foreach(Match m in (Regex.Matches("Jack_Sparrow","[^A-Za-z ]")) { Console.WriteLine("{0} found at index{1}",m.Value,m.Index); }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜