Regex to prevent trailing spaces and extra spaces

不问归期 提交于 2021-02-05 07:10:27

问题


Right now I have a regex that prevents the user from typing any special characters. The only allowed characters are A through Z, 0 through 9 or spaces.

I want to improve this regex to prevent the following:

  1. No leading/training spaces - If the user types one or more spaces before or after the entry, do not allow.
  2. No double-spaces - If the user types the space key more than once, do not allow.

The Regex I have right now to prevent special characters is as follows and appears to work just fine, which is:

^[a-zA-Z0-9 ]+$

Following some other ideas, I tried all these options but they did not work:

^\A\s+[a-zA-Z0-9 ]+$\A\s+
/s*^[a-zA-Z0-9 ]+$/s*

Could I get a helping hand with this code? Again, I just want letters A-Z, numbers 0-9, and no leading or trailing spaces.

Thanks.


回答1:


You can use the following regex:

^[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*$

See regex demo.

The regex will match alphanumerics at the start (1 or more) and then zero or more chunks of a single space followed with one or more alphanumerics.

As an alternative, here is a regex based on lookaheads (but is thus less efficient):

^(?!.* {2})(?=\S)(?=.*\S$)[a-zA-Z0-9 ]+$

See the regex demo

The (?!.* {2}) disallows consecutive spaces and (?=.*\S$) requires a non-whitespace to be at the end of the string and (?=\S) requires it at the start.



来源:https://stackoverflow.com/questions/35373046/regex-to-prevent-trailing-spaces-and-extra-spaces

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