C# Regular Expression to match letters, numbers and underscore

前端 未结 4 878
感动是毒
感动是毒 2020-12-29 03:29

I am trying to create a regular expression pattern in C#. The pattern can only allow for:

  • letters
  • numbers
  • underscores

So far I

相关标签:
4条回答
  • 2020-12-29 04:08

    EDIT :

    @"^[a-zA-Z0-9\_]+$"
    

    or

    @"^\w+$"
    
    0 讨论(0)
  • 2020-12-29 04:13

    @"^\w+$"

    \w matches any "word character", defined as digits, letters, and underscores. It's Unicode-aware so it'll match letters with umlauts and such (better than trying to roll your own character class like [A-Za-z0-9_] which would only match English letters).

    The ^ at the beginning means "match the beginning of the string here", and the $ at the end means "match the end of the string here". Without those, e.g. if you just had @"\w+", then "@@Foo@@" would match, because it contains one or more word characters. With the ^ and $, then "@@Foo@@" would not match (which sounds like what you're looking for), because you don't have beginning-of-string followed by one-or-more-word-characters followed by end-of-string.

    0 讨论(0)
  • 2020-12-29 04:22

    Try experimenting with something like http://www.weitz.de/regex-coach/ which lets you develop regex interactively.

    It's designed for Perl, but helped me understand how a regex works in practice.

    0 讨论(0)
  • 2020-12-29 04:23

    Regex

    packedasciiRegex = new Regex(@"^[!#$%&'()*+,-./:;?@[\]^_]*$");
    
    0 讨论(0)
提交回复
热议问题