PHP:正则表达式语法


PHP: RegEx Syntax

我是一个正则表达式的新手,所以请忽略我的错误。我需要确保满足字符串中的几个条件。

要求:

  • 最多 5 个字
  • 最多 256 个字符
  • Word 被视为 1 个或多个字符 - 没有空格
  • 不应包含两个连续的空格

例:

  • 树在风中飘扬
  • 1-树倒下

失败示例:

  • 树在夜空中吹拂
  • 树在夜间折断2条树枝

这可以在一个表达式中完成还是应该分解?

验证 2 个空格:

- /^'s's$/

最多 256 个字符:

- /^[a-zA-Z0-9]{,256}$/

不确定如何测试这 5 个单词的案例并结合我强加的其他标准。谁能帮忙?

测试单词:

- /^'w{1,5}$

你可以试试这个:

(?s)'A(?!.{257}|.*'s's)'W*'w*(?:'W+'w+){0,4}'W*'z

图案详情:

(?s)          # turn on the singleline mode: allow the dot to match newlines
'A            # start of the string anchor
(?!           # open a negative lookahead assertion: means not followed by
    .{257}    # 257 characters
  |           # OR
    .*'s's    # two consecutive whitespaces
)             # close the negative lookahead
'W*           # optional non-word characters
'w*           # optional word characters (nothing in your requirements forbids to have a string without words or an empty string)
(?:           # open a non-capturing group
    'W+       # non-word characters: words are obviously separated with non-word characters
    'w+       # an other word 
){0,4}        # repeat the non-capturing group between zero and 4 times
'W*           # optional non-word characters
'z            # anchor for the end of the string