简体   繁体   English

正则表达式在开始或结束时没有空格,但允许中间有空格但也只允许一个字符输入

[英]Regular expression for no space at start or end, but allow space in middle but also allow only one char inputs

My RegExp is我的RegExpRegExp

/^[A-Za-z ]*$/

Then what should i write to not allow space at start or end, but allow space in middle那么我应该写什么来不允许在开始或结束时有空格,但在中间允许空格

此正则表达式将匹配符合原始表达式且开头或结尾没有空格的任何字符串

^(?! )[A-Za-z ]*(?<! )$

Use this pattern to match in a regex使用此模式匹配正则表达式

(?=(?:^\w))([A-Za-z ]+)(?<=[^ ])$

Demo演示

http://regex101.com/r/lM1aQ6 http://regex101.com/r/lM1aQ6

I suggest You to use trim() in php to remove the space at the start and end of the string.我建议您在 php 中使用trim()删除字符串开头和结尾的空格。

$hello  = " Hello World ";
trim($hello);

From the PHP Doc来自PHP 文档

trim — Strip whitespace (or other characters) from the beginning and end of a string trim — 从字符串的开头和结尾去除空格(或其他字符)

I would probably split the problem: or it contains no spaces at all, or it contains only in the middle.我可能会拆分问题:或者它根本不包含空格,或者它只包含在中间。

^[A-Za-z]*$|^[A-Za-z][A-Za-z ]*[A-Za-z]$

It will accept "aa", "a", "a ab c", but not " " or " a"...它将接受“aa”、“a”、“a ab c”,但不接受“”或“a”...

I think you need this:我认为你需要这个:

<?php 
echo trim("  spaces and spaces    "); // outputs: "spaces and spaces"
?>

I think it will for you,我想这对你来说,

\b^([^\s]|[a-zA-Z])\s+[a-zA-Z]\b

Here,这里,

  • \\b denotes word boundary. \\b 表示词边界。
  • ^\\s to disallow white-space. ^\\s 禁止空格。
  • | | is an alternation是一个交替

And thanks for sharing.并感谢分享。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM