【问题标题】:RegExr with minimum 2 letter and optional letters, but no other letters?RegExr 至少有 2 个字母和可选字母,但没有其他字母?
【发布时间】:2019-07-05 19:06:15
【问题描述】:

我想要一个文本的正则表达式,如果其中至少有 1 个带有 2 个字母的单词,并且至少有 25 个字母或数字并且还允许 (0-9äöü,.' -),如果有其他字母或数字,则允许它,应该报错。


例子:

正确:

  • 约翰·多伊
  • 马克斯·穆斯特曼
  • John-Frank' Doe。

错误:

  • 约翰/多伊

正则表达式:

  • 字正则表达式:([a-z]{2})\w+
  • 允许的项目:[äöü0-9,.' -]
  • 最大长度:{25,999}
if(preg_match("/([A-Za-z]{2})\w+/",$text)){
    if(!preg_match("/[a-zäöüA-ZÄÖÜ,.' -]/g",$text)){echo 'error';}
else{echo'error';}

我不确定如何在代码中获得解决方案。

【问题讨论】:

  • . 不应该是\.
  • 在字符集中,\对于点是可选的

标签: php regex


【解决方案1】:

您可能会做的是使用积极的前瞻来断言 25 - 999 的长度,并断言有 2 个连续的[a-z]

然后将您的字符类 [a-zA-Z0-9äöü,.' -]+ 与添加 a-z 和 A-Z 的允许项目匹配。

^(?=.{25,999})(?=.*[a-z]{2})[a-zA-Z0-9äöü,.' -]+$
  • ^ 字符串开始
  • (?=.{25,999}) 正向前瞻,断言 25 - 99 个字符
  • (?=.*[a-z]{2}) 正向前瞻,断言 2 次 [a-z]
  • [a-zA-Z0-9äöü,.' -]+ 匹配任何列出的 1 次以上
  • $字符串结束

Regex demo | Php demo

例如(我将字符串加长以考虑最小长度 25)

$strings = [
    "This is a text with John Doe",
    "This is a text with Max Müstermann ",
    "This is a text withJohn-Frank' Doe.",
    "This is a text with John/Doejlkjkjlk",
];
$pattern = "/^(?=.{25,999})(?=.*[a-z]{2})[a-zA-Z0-9äöü,.' -]+$/";
foreach ($strings as $string) {
    if (preg_match($pattern, $string)) {
        echo "Ok ==> $string" . PHP_EOL;
    } else {
        echo "error" . PHP_EOL;
    }
}

结果

Ok ==> This is a text with John Doe
Ok ==> This is a text with Max Müstermann 
Ok ==> This is a text withJohn-Frank' Doe.
error

【讨论】:

  • 如果你有更多的行,它会产生问题,但你可以添加一个\n!但是为什么你在 php 代码中有两次“[a-zA-Z0-9äöü,.' -]*" 在模式中?
  • @klediooo 这只是编写pattern 的另一种方式,而无需一次前瞻。我已经用初始模式更新了答案。
猜你喜欢
  • 1970-01-01
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 2015-05-24
  • 2022-11-16
  • 1970-01-01
  • 2016-06-04
  • 2019-11-09
相关资源
最近更新 更多