regex check for white space in middle of string

前端 未结 5 1957
感情败类
感情败类 2020-12-16 14:08

I want to validate that the characters are alpha numeric:

Regex aNum = Regex(\"[a-z][A-Z][0-9]\");

I want to add the option that there migh

相关标签:
5条回答
  • 2020-12-16 14:52
    "[A-Za-z0-9\s]*"
    

    matches alphanumeric characters and whitespace. If you want a word that can contain whitespace but want to ensure it starts and ends with an alphanumeric character you could try

    "[A-Za-z0-9][A-Za-z0-9\s]*[A-Za-z0-9]|[A-Za-z0-9]"
    
    0 讨论(0)
  • 2020-12-16 14:58

    If you want to check for white space in middle of string you can use these patterns :

    1. "(\w\s)+" : this must match a word with a white space at least.
    2. "(\w\s)+$" : this must match a word with a white space at least and must finish with white space.
    3. "[\w\s]+" : this match for word or white space or the two.
    0 讨论(0)
  • 2020-12-16 15:00

    [A-Za-z0-9\s]{1,} should work for you. It matches any string which contains alphanumeric or whitespace characters and is at least one char long. If you accept underscores, too you shorten it to [\w\s]{1,}.

    You should add ^ and $ to verify the whole string matches and not only a part of the string:

    ^[A-Za-z0-9\s]{1,}$ or ^[\w\s]{1,}$.

    0 讨论(0)
  • 2020-12-16 15:04

    Exactly two words with single space:

    Regex aNum = Regex("[a-zA-Z0-9]+[\s][a-zA-Z0-9]+");
    

    OR any number of words having any number of spaces:

    Regex aNum = Regex("[a-zA-Z0-9\s]");
    
    0 讨论(0)
  • 2020-12-16 15:04

    To not allow empty strings then

    Regex.IsMatch(s ?? "",@"^[\w\s]+$"); 
    

    and to allow empty strings

    Regex.IsMatch(s ?? "",@"^[\w\s]*$"); 
    

    I added the ?? "" as IsMatch does not accept null arguments

    0 讨论(0)
提交回复
热议问题