.NET RegEx for letters and spaces

后端 未结 5 826
庸人自扰
庸人自扰 2020-12-16 23:44

I am trying to create a regular expression in C# that allows only alphanumeric characters and spaces. Currently, I am trying the following:

string pattern =          


        
相关标签:
5条回答
  • 2020-12-17 00:10

    The character class \w does not match spaces. Try replacing it with [\w ] (there's a space after the \w to match word characters and spaces. You could also replace the space with \s if you want to match any whitespace.

    0 讨论(0)
  • 2020-12-17 00:14

    If you just need English, try this regex:

    "^[0-9A-Za-z ]+$"

    The brackets specify a set of characters

    0-9: All digits

    A-Z: All capital letters

    a-z: All lowercase letters

    ' ': Spaces

    If you need unicode / internationalization, you can try this regex:

    "^[\\w ]+$"

    This regex will match all unicode letters and numbers and space, which may be more than you need, so if you just need English or basic Roman characters, the first regex will be simpler and faster to execute.

    Note that for both regex I have included the ^ and $ operator which mean match at start and end. If you need to pull this out of a string and it doesn't need to be the entire string, you can remove those two operators.

    0 讨论(0)
  • 2020-12-17 00:14

    try this for all letter with space :

    @"[\p{L} ]+$"
    
    0 讨论(0)
  • 2020-12-17 00:22

    If, other then 0-9, a-z and A-Z, you also need to cover any accented letters like ï, é, æ, Ć or Ş then you should better use the Unicode properties \p{...} for matching, i.e. (note the space):

    string pattern = @"^[\p{IsLetter}\p{IsDigit} ]+$";
    
    0 讨论(0)
  • 2020-12-17 00:35

    This regex works great for me.

               Regex rgx = new Regex("[^a-zA-Z0-9_ ]+");
                if (rgx.IsMatch(yourstring))
                {
                    var err = "Special charactes are not allowed in Tags";
                }
    
    0 讨论(0)
提交回复
热议问题