正则表达式不允许只空格? [英] RegEx expression not allowing only spaces?

查看:52
本文介绍了正则表达式不允许只空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 regEx 表达式,它只允许空格、字母和破折号.我想修改它,这样它也不允许只使用空格.有人可以帮我吗?

I have this regEx expression which allows only spaces, letters and dashes. I'd like to modify it so it wouldn't allow ONLY spaces too. Can someone help me ?

/^([A-zăâîșțĂÂÎȘȚ-\s])+$/

推荐答案

您可以使用否定前瞻来限制这种通用模式:

You can use a negative lookahead to restrict this generic pattern:

/^(?!\s+$)[A-Za-zăâîșțĂÂÎȘȚ\s-]+$/
  ^^^^^^^^

查看正则表达式演示

(?!\s+$) 前瞻在最开始执行一次,如果在字符串末尾有 1 个或多个空格,则返回 false.

The (?!\s+$) lookahead is executed once at the very beginning and returns false if there are 1 or more whitespaces until the end of the string.

此外,您的正则表达式包含一个经典的 [Az] 问题,它不仅仅匹配 ASCII 字母,您需要将其替换为 [A-Za-z](或者只是 [az] 并使用 /i 不区分大小写的修饰符).

Also, your regex contained a classical issue of [A-z] that matches more than just ASCII letters, you need to replace this with [A-Za-z] (or just [a-z] and use the /i case insensitive modifier).

此外,字符类中的 - 通常放在最后以免转义它,它将被解析为文字连字符(但是,如果另一个开发人员将不得不通过向字符类添加更多符号来更新此模式).

Also, the - inside a character class is usually placed at the end so as not to escape it, and it will be parsed as a literal hyphen (however, you might want to escape it if another developer will have to update this pattern by adding more symbols to the character class).

以防万一这是一个不支持环视的正则表达式引擎:

And just in case this is a regex engine that does not support lookarounds:

^[A-Za-zăâîșțĂÂÎȘȚ\s-]*[A-Za-zăâîșțĂÂÎȘȚ-][A-Za-zăâîșțĂÂÎȘȚ\s-]*$

它需要至少 1 个来自允许集中的非空格字符(也匹配 1 个强制符号).

It requires at least 1 non-space character from the allowed set (also matching 1 obligatory symbol).

另一个正则表达式演示

这篇关于正则表达式不允许只空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆