简体   繁体   中英

Regular expression any character but a white space

I'm creating a password validator which takes any character but whitespaces and with at least 6 characters.

After searching the best I came up is this is this example: What is the regular expression for matching that contains no white space in between text?

It disallows any spaces inbetween but does allow starting and ending with a space. I want to disallow any space in the string passed.

I tried this but it doesn't work:

if (preg_match("/^[^\s]+[\S+][^\s]{6}$/", $string)) {
  return true;
} else {
  return false;
}

Thanks.

The simplest expression:

^\S{6,}$

^ means the start of the string
\\S matches any non-whitespace character
{6,} means 6 or more
$ means the end of the string

In PHP, that would look like

preg_match('/^\S{6,}$/', $string)

Edit:

>> preg_match('/^\S{6,}$/', "abcdef\n")
1
>> preg_match('/^\S{6,}\z/', "abcdef\n")
0
>> preg_match('/^\S{6,}$/D', "abcdef\n")
0

Qtax is right. Good call! Although if you're taking input from an HTML <input type="text"> you probably won't have any newlines in it.

Something like this:

/^\S{6,}\z/

Can be quoted like:

preg_match('/^\S{6,}\z/', $string)

All answers using $ are wrong (at least without any special flags). You should use \\z instead of $ if you do not want to allow a line break at the end of the string.

  • $ matches end of string or before a line break at end of string (if no modifiers are used)
  • \\z matches end of string (independent of multiline mode)

From http://www.pcre.org/pcre.txt :

 ^           start of subject
              also after internal newline in multiline mode
 \A          start of subject
 $           end of subject
              also before newline at end of subject
              also before internal newline in multiline mode
 \Z          end of subject
              also before newline at end of subject
 \z          end of subject

\\S - Matches any non-white-space character. Equivalent to the Unicode character categories [^\\f\\n\\r\\t\\v\\x85\\p{Z}] . If ECMAScript-compliant behavior is specified with the ECMAScript option, \\S is equivalent to [^ \\f\\n\\r\\t\\v] .

The start of string you can do : ^[ \\t]+ , and for end : [ \\t]+$ (tab and spaces)

ETA:

By the way, you regex [\\S+] , i think you're looking for : [\\S]+

I think you should be fine using the following, which would match any string longer than 1 character with no whitespace:

^[^\s]+$

You can see the test here: http://regexr.com?2ua2e .

Try this. This will match at least 6 non whitespace characters followed by any number of additional non whitespace characters.

^[^\s]{6}[^\s]*$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM