正则表达式以防止尾随空格和额外空格 [英] Regex to prevent trailing spaces and extra spaces
问题描述
现在我有一个正则表达式可以防止用户输入任何特殊字符.唯一允许的字符是 A 到 Z、0 到 9 或空格.
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:
- 没有前导/训练空格 - 如果用户在条目之前或之后输入一个或多个空格,则不允许.
- 禁止双空格 - 如果用户多次键入空格键,则不允许.
我现在用来防止特殊字符的正则表达式如下所示,看起来工作得很好,即:
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*
我可以帮忙处理这个代码吗?同样,我只想要字母 A-Z、数字 0-9,并且没有前导或尾随空格.
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.
谢谢.
推荐答案
您可以使用以下正则表达式:
You can use the following regex:
^[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*$
参见正则表达式演示.
正则表达式将匹配开头的字母数字(1 个或多个),然后匹配单个空格的零个或多个块,后跟一个或多个字母数字.
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 ]+$
查看正则表达式演示
(?!.* {2})
不允许连续空格,(?=.*\S$)
要求末尾有一个非空格字符串和 (?=\S)
在开始时需要它.
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.
这篇关于正则表达式以防止尾随空格和额外空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!