gpt4 book ai didi

php - preg_match 中的符号是什么意思?

转载 作者:可可西里 更新时间:2023-11-01 13:07:27 25 4
gpt4 key购买 nike

我在离线借用的代码片段中有这个表达式。它强制新用户的密码不仅需要大写+小写+数字,而且必须按此顺序!如果我输入 lower+upper+numbers,它会失败!

if (preg_match("/^.*(?=.{4,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $pw_clean, $matches)) {

我在网上搜索过,但找不到可以告诉我某些字符含义的资源。我可以看到模式是 preg_match("/some expression/",yourstring,your match).

这些是什么意思:

1.  ^          -  ???
2. .* - ???
3. (?=.{4,}) - requires 4 characters minimum
4. (?.*[0-9]) - requires it to have numbers
5. (?=.*[a-z])- requires it to have lowercase
6. (?=.*[A-Z])- requires it to have uppercase
7. .*$ - ???

最佳答案

这里是直接的答案。我保持简短是因为如果不了解正则表达式,它们就没有意义。最好在 regular-expressions.info 上获得这种理解。我建议你也试试 regex helper tools列在那里,它们允许您进行实验 - 在您编辑模式时查看实时捕获/匹配,非常有帮助。


1:插入符号^是一个 anchor ,意思是“大海捞针/字符串/线的开始”。

  • 如果脱字符是字符类 [] 中的第一个符号,则它具有不同的含义:它否定该类。 (所以在 [^ab] 中,插入符号使该类匹配任何不是 ab 的东西)

2:点 . 和星号 * 有两个不同的用途:

  • 点匹配除换行符\n之外的任何单个字符。
  • 星号表示“允许零个或多个前面的类型”。

当这两个组合为 .* 时,它基本上读取“零个或多个任何内容,直到换行符或另一个规则生效”。

7: 美元 $ 也是一个像插入符号一样的 anchor ,具有相反的功能:“大海捞针的尽头”。


编辑:

用简单的括号 ( ) 将某物括起来使其成为一个。这里有 (?=),这是一个断言,特别是一个正向预测断言。它所做的只是检查从大海捞针中的当前光标位置向前是否确实存在内部内容。还在我身边吗?
示例: foo(?=bar) 匹配 foo 仅当后跟 barbar 永远不会匹配,只返回 foo

考虑到这一点,让我们剖析您的正则表达式:

/^.*(?=.{4,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/

Reads as:
^.* From Start, capture 0-many of any character
(?=.{4,}) if there are at least 4 of anything following this
(?=.*[0-9]) if there is: 0-many of any, ending with an integer following
(?=.*[a-z]) if there is: 0-many of any, ending with a lowercase letter following
(?=.*[A-Z]) if there is: 0-many of any, ending with an uppercase letter following
.*$ 0-many of anything preceding the End

你说密码字符的顺序很重要——在我的测试中没有。请参阅下面的测试脚本。希望这能解决一两件事。如果您正在寻找另一个更宽容的正则表达式,请参阅 regex password validation

<pre>
<?php
// Only the last 3 fail, as they should. You claim the first does not work?
$subjects = array("aaB1", "Baa1", "1Baa", "1aaB", "aa1B", "aa11", "aaBB", "aB1");

foreach($subjects as $s)
{
$res = preg_match("/^.*(?=.{4,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $s, $matches);
echo "result: ";
print_r($res);

echo "<br>";
print_r($matches);
echo "<hr>";
}

用于检查和测试正则表达式的优秀在线工具: https://regex101.com/

关于php - preg_match 中的符号是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10201337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com