正则表达式,仅允许特定格式。 “约翰·多伊”

时间:2016-02-27 17:47:55

标签: php regex

我已经研究了一点,但我发现没有任何东西与我需要的东西完全相关,每当试图创建表达时,它总是与我的要求有点不同。

我试图采用[AZaz09]{3,8}\-[AZaz09]{3,8}

的方式

我希望有效结果只允许使用文本文本,其中或者文本可以是字母或数字,但是唯一允许的符号是-,而且位于两个文本之间。

每个文本的长度必须至少为三个字符({3,8}?),然后用-分隔。

因此,有效的例子可能是:

Text-Text
Abc-123
123-Abc
A2C-def4gk

无效的测试可能是:

Ab-3
Abc!-ajr4
a-bc3-25aj
a?c-b%

6 个答案:

答案 0 :(得分:11)

您需要使用锚点并使用^[A-Za-z0-9]{3,8}-[A-Za-z0-9]{3,8}$ ,以便将字符类中的字符作为范围读取,而不是单个字符。

尝试:

i

演示:https://regex101.com/r/xH3oM8/1

您也可以使用\d修饰符和(?i)^[a-z\d]{3,8}-[a-z\d]{3,8}$ 元字符来简化它。

<div ng-if="user != null && user != 'Error'">CONTENT</div>

答案 1 :(得分:6)

如果允许重音字母或Unicode范围内存在的任何其他字母(如希腊语或西里尔字母),则使用u修饰符(对于UTF-8支持)和\pL匹配Unicode字母(和数字\d):

$string ="
Mañana-déjà
Text-Text
Abc-123
123-Abc
A2C-def4gk
Ab-3
Abc!-ajr4
a-bc3-25aj
a?c-b%";

$regex='/^[\pL\d]{3,}-[\pL\d]{3,}$/mu';

preg_match_all($regex, $string, $matches);

var_export($matches);

输出:

array (
  0 => 
  array (
    0 => 'Mañana-déjà',
    1 => 'Text-Text',
    2 => 'Abc-123',
    3 => '123-Abc',
    4 => 'A2C-def4gk',
  ),
)

注意:与\w的区别在于[\pL\d]与下划线不匹配。

答案 2 :(得分:5)

您可以提出以下建议:

<?php
$string ="
Text-Text
Abc-123
123-Abc
A2C-def4gk
Ab-3
Abc!-ajr4
a-bc3-25aj
a?c-b%";

$regex='~
        ^\w{3,}  # at last three word characters at the beginning of the line
        -        # a dash
        \w{3,}$  # three word characters at the end of the line
        ~xm';    # multiline and freespacing mode (for this explanation)
                 # ~xmu for accented characters

preg_match_all($regex, $string, $matches);
print_r($matches);
?>

正如@ chris85指出的那样,\w也会匹配下划线。 Trincot有一个很好的评论(匹配重音字符,即)。为实现这一目标,simply use the u modifier 请参阅a demo on regex101.coma complete code on ideone.com

答案 3 :(得分:3)

您可以使用此正则表达式

^\w{3,}-\w{3,}$

^       // start of the string
\w{3,}  // match "a" to "z", "A" to "Z" and 0 to 9 and requires at least 3 characters
-       // requires "-"
\w{3,}  // same as above
$       // end of the string

Regex Demo

答案 4 :(得分:2)

还有一个简短的。

^([^\W_]{3,8})-(?1)$

Demo at regex101

我对@ chris85的投票是最明显和最高效的。

答案 5 :(得分:1)

这一个

^([\w]{3,8}-[\w]{3,8})$

https://regex101.com/r/uS8nB5/1

相关问题