Regex to validate string for having three non white-space characters

拥有回忆 提交于 2019-12-31 05:16:27

问题


I am using parsley js for validating input and I am using the data-parsley-pattern which allows me to pass in regular expression.

I am trying to validate the string to make sure it contains AT LEAST three non white space characters. Below is strings that should be invalid or valid.

valid: 1 2   b
invalid: 1 b [space]
valid: 3x c 1 3n
invalid: 1      b

[space] = is just a white space, only used it in that example because it was at the end of the string, in all the other examples, the spaces between the characters represents there are white spaces.

I tried:

\S{3}

without success

and

[\S{3}]

回答1:


\S{3,}

\S{3,} match any non-white space character [^\r\n\t\f ]

Quantifier: {3,} Between 3 and unlimited times, as many times as possible, giving back as needed [greedy]

e.g. abc or abc def

https://regex101.com/r/gO6sT3/1


That, as pointed out by Wiktor Stribiżew, only matches consecutive characters. If you mean "the input can have any number of whitespaces, anywhere, as long as there are at least three non-whitespace characters anywhere" then maybe:

.*\S.*\S.*\S.*

Anything or nothing, non-witespace, anything or nothing, non-whitespace, etc.

e.g. a b c or ab c or abc

https://regex101.com/r/wY0kL4/1

Also see anything and everything at the site: http://www.regular-expressions.info/




回答2:


"[^\s][^\s][^\s]+"
[] contains a character class.
/s is a whitespace character.
^ works kind of like a logical not.
The + catches one or more of the previous character
You may need to add more backslashes depending on any special escape characters



来源:https://stackoverflow.com/questions/38336983/regex-to-validate-string-for-having-three-non-white-space-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!