Regular Expressions: low-caps, dots, zero spaces

后端 未结 4 916
梦毁少年i
梦毁少年i 2021-01-24 13:09

how do I write an expression which checks for lowcaps, dots, and without any white space in the string?

the code below so far was trying to check for lowcaps and dots (i

4条回答
  •  闹比i
    闹比i (楼主)
    2021-01-24 13:27

     /^[a-z0-9.]+$)/
    

    Should do it. Just think about that only small letters, dots and digits are allowed. The expression will not match if any white-space is included. Btw. you don't have to escape meta-characters in a capture group.

    ^ and $ indicates that the whole string should only contain those characters in the capture group (they mark the start and the end of the string) and the + says that at least one of these characters must occur. Depending on your needs you can change it to e.g. {3,} which means that the string must be at least 3 characters long.

    Example:

    $values=array("fooBar", "123.45", "foo bar", "foo.bar");
    
    foreach($values as $value) {
        if (!preg_match('/^[a-z0-9.]+$/', $value))
        {
             echo "Not valid: $value\n";
        }
    }
    

    prints:

    Not valid: fooBar
    Not valid: foo bar
    

提交回复
热议问题