正则表达式只接受字母和空格,并且在字符串的开头和结尾不允许使用空格 [英] Regex to accept only alphabets and spaces and disallowing spaces at the beginning and the end of the string

查看:112
本文介绍了正则表达式只接受字母和空格,并且在字符串的开头和结尾不允许使用空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对验证输入字段具有以下要求:

I have the following requirements for validating an input field:

  1. 它只能包含字母和字母之间的空格.
  2. 该字符串的开头或结尾不能包含空格.
  3. 它不能包含任何其他特殊字符.

我为此使用了以下正则表达式:

I am using following regex for this:

^(?!\s*$)[-a-zA-Z ]*$

但这是在开头留有空格.感谢您的帮助.

But this is allowing spaces at the beginning. Any help is appreciated.

推荐答案

对我而言,唯一可行的方法是:

For me the only logical way to do this is:

^\p{L}+(?: \p{L}+)*$

字符串的开头必须至少有一个字母.(我用Unicode代码属性将您的 [a-zA-Z] 替换为字母 \ p {L} ).然后可以有一个空格,后跟至少一个字母,此部分可以重复.

At the start of the string there must be at least one letter. (I replaced your [a-zA-Z] by the Unicode code property for letters \p{L}). Then there can be a space followed by at least one letter, this part can be repeated.

\ p {L} :来自任何语言的任何字母.参见 regular-expressions.info

\p{L}: any kind of letter from any language. See regular-expressions.info

表达式 ^(?!\ s * $)中的问题是,如果只有空格至字符串末尾,则超前查询将失败.如果要禁止前导空格,则只需删除lookahead ==> ^(?!\ s)[-a-zA-Z] * $ 中字符串锚的末尾.但这仍然允许字符串以空格结尾.为避免这种情况,请回顾字符串 ^(?!\ s)[-a-zA-Z] *(?<!\ s)$ 的末尾.但是我认为对于此任务,不需要四处看看.

The problem in your expression ^(?!\s*$) is, that lookahead will fail, if there is only whitespace till the end of the string. If you want to disallow leading whitespace, just remove the end of string anchor inside the lookahead ==> ^(?!\s)[-a-zA-Z ]*$. But this still allows the string to end with whitespace. To avoid this look back at the end of the string ^(?!\s)[-a-zA-Z ]*(?<!\s)$. But I think for this task a look around is not needed.

这篇关于正则表达式只接受字母和空格,并且在字符串的开头和结尾不允许使用空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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