【问题标题】:Regular Expression to match only letters numbers and spaces正则表达式仅匹配字母数字和空格
【发布时间】:2012-01-29 10:23:44
【问题描述】:

我不擅长正则表达式。

我不想允许任何其他字符,但字母空格和数字。 当然,用户可以只输入字母或只输入数字或字母和数字,但不能输入其他字符。他也可以将 _ 放在字符串之间,例如:

Hello_World123

这可能是字符串。谁能帮我建立一个正则表达式?

【问题讨论】:

  • 是否允许空字符串?是否允许使用非 ASCII 字母/数字?
  • “任何人都可以帮我建立 [sic.] 一个 [sic.] 正则表达式吗”?您最好自己学习正则表达式,而不是期望社区为您编写它们。对于初学者,请参阅regular-expressions.info 的教程。
  • @Johnsyweb 抱歉,我很着急,我马上就需要了。我肯定会学习它们。谢谢=)
  • 大概你会给蒂姆佣金!

标签: jquery regex character


【解决方案1】:

要确保字符串仅包含 (ASCII) 字母数字字符、下划线和空格,请使用

^[\w ]+$

说明:

^       # Anchor the regex at the start of the string
[\w ]   # Match an alphanumeric character, underscore or space
+       # one or more times
$       # Anchor the regex at the end of the string

【讨论】:

    【解决方案2】:

    简单地说:

    ^[\w ]+$
    

    解释:

    ^ matches the start of the string
    \w matches any letter, digit, or _, the same as [0-9A-Za-z_]
    [\w ] is a set that that matches any character in \w, and space
    + allows one or more characters
    $ matches the end of the string
    

    【讨论】:

    • 也应该允许空格。
    • @TimPietzcker:是的,我错过了。谢谢。
    【解决方案3】:

    你可以使用 [\w \d]+ 。你可以试试http://gskinner.com/RegExr/

    【讨论】:

    • 这不允许空格。并且不推荐w3schools。这是最糟糕的资源之一。
    • 编辑了答案。 @TimPietzcker 感谢您指出这一点
    • 仍然不正确。没有锚点,\d 已经包含在 \w 中。
    猜你喜欢
    • 2010-09-15
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 2019-10-14
    • 1970-01-01
    相关资源
    最近更新 更多