我已经研究了一点,但我发现没有任何东西与我需要的东西完全相关,每当试图创建表达式时,它总是与我的要求有点不同.
我尝试了一些类似的东西[AZaz09]{3,8}\-[AZaz09]{3,8}.
我希望有效结果只允许文本文本,其中或者文本可以是字母或数字,但是唯一允许的符号是-两个文本之间.
每个文本必须至少有三个字符长({3,8}?),然后用-.分隔.
因此,为了使其有效,一些例子可能是:
Text-Text
Abc-123
123-Abc
A2C-def4gk
Run Code Online (Sandbox Code Playgroud)
无效的测试可能是:
Ab-3
Abc!-ajr4
a-bc3-25aj
a?c-b%
Run Code Online (Sandbox Code Playgroud)
chr*_*s85 11
您需要使用锚点并使用它,-以便将字符类中的字符作为范围读取,而不是单个字符.
尝试:
^[A-Za-z0-9]{3,8}-[A-Za-z0-9]{3,8}$
Run Code Online (Sandbox Code Playgroud)
演示:https://regex101.com/r/xH3oM8/1
您也可以使用i修饰符和\d元字符简化它.
(?i)^[a-z\d]{3,8}-[a-z\d]{3,8}$
Run Code Online (Sandbox Code Playgroud)
如果允许重音字母,或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);
Run Code Online (Sandbox Code Playgroud)
输出:
array (
0 =>
array (
0 => 'Mañana-déjà',
1 => 'Text-Text',
2 => 'Abc-123',
3 => '123-Abc',
4 => 'A2C-def4gk',
),
)
Run Code Online (Sandbox Code Playgroud)
注意:区别\w在于[\pL\d]与下划线不匹配.
你可以拿出以下内容:
<?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);
?>
Run Code Online (Sandbox Code Playgroud)
正如@ chris85指出的那样,\w也会匹配下划线.Trincot有一个很好的评论(匹配重音字符,即).要实现此目的,只需使用u修饰符即可.
请参见上regex101.com演示和上ideone.com一个完整的代码.