简体   繁体   English

PHP正则表达式:或子句不起作用

[英]php regex: or clause doesn't work

i need to write a regex for make a double check: if a string contains empty spaces at the beginning, at the end, and if all string it's composed by empty spaces, and if string contains only number. 我需要编写一个正则表达式进行仔细检查:字符串是否在开头,结尾都包含空格,并且是否所有字符串都由空格组成,并且字符串是否仅包含数字。 I've write this regex 我写了这个正则表达式

 $regex = '/^(\s+ )| ^(\d+)$/';

but it doesn't' work. 但这行不通。 What's wrong ? 怎么了 ?

The space before ^(\\d+) make your regex can't catch the numeric string. ^(\\d+)之前的空格使您的正则表达式无法捕获数字字符串。

It should be like below: 它应该像下面这样:

$regex = '/^\s*\d*\s*$/';

First if all, remove the space between | 首先,如果要除去|之间的空格。 and ^. 和^。 You are trying to match a space before the beginning of the line (^), so that can not work. 您正在尝试在行首(^) 之前匹配一个空格,因此无法正常工作。

I do not exactly understand what you want. 我不完全了解您想要什么。 Either a string that only consists of white spaces, or a number that may have white spaces at the beginning or end? 仅包含空格的字符串,还是开头或结尾可能包含空格的数字? Try this: 尝试这个:

$regex = '/^\s*\d*\s*$/';

First things first: get your spaces right! 第一件事:正确利用空间!
For example (\\s+ ) will match a minimum of one space ( \\s+ ) followed by another space ( 例如(\\s+ )至少匹配一个空格( \\s+ ),然后再匹配另一个空格( )! )! Same applies for the space between | 之间的空格也是如此| and ^ . ^ This way you will match the space literally every time and this leads to wrong results. 这样,您每次都会真正匹配该空间,这将导致错误的结果。

If I get you right and you want to match on strings which 如果我说对了,而您想匹配的字符串

  • start with one or more spaces OR 以一个或多个空格开头或
  • end with one or more spaces OR 以一个或多个空格结尾或
  • consist only of spaces OR 仅包含空格或
  • consist only of numbers 仅由数字组成

I'd use 我会用

/^(?:\s+.*|.*\s+$|\d+$)/

Demo @ regex101 演示@ regex101

This way you match spaces at the start of the string ( \\s+.* ) or ( | ) spaces at the end of the string ( .*\\s+$ ) or a completely numeric string ( \\d+$ ). 这样,您可以匹配字符串开头( \\s+.* )的空格或字符串( .*\\s+$ )末尾的( | )空格或完全数字的字符串( \\d+$ )。
Insert capturing groups as needed. 根据需要插入捕获组。

This will match in case the whole string consists of spaces, too, because technically the string then starts with spaces. 如果整个字符串也由空格组成,这将匹配,因为从技术上讲,字符串然后以空格开头。

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

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