2016-02-27 78 views
7

我已經研究了一下,但是我沒有發現任何與我需要的東西完全相關的東西,每當試圖創建表達式時,它總是與我需要的東西有點偏離。正則表達式,只允許specfic格式。 「John-doe」

我試圖沿着[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% 
+1

你想重音字母或其他字母也匹配?像「déjà-vus」,「12μ-13μ」,「mañana-1234」 – trincot

+0

@trincot:好點,已經更新了我的答案以反映'u'修飾符。 – Jan

回答

10

您需要使用錨,並在字符類使用-這樣的人物被讀作範圍,而不是單個字符。

嘗試:

^[A-Za-z0-9]{3,8}-[A-Za-z0-9]{3,8}$ 

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

你也可以把它簡化,但與i修改和\d元字符。

(?i)^[a-z\d]{3,8}-[a-z\d]{3,8}$ 
+0

頂部一個似乎是我的使用完美:) – mhvvzmak1

+0

我注意到,在該網站有/ gm在正則表達式的結尾,這個gm做什麼,它是必需的? – mhvvzmak1

+2

'g'是一個全局修飾符,'m'是多行的。那只是爲了在那裏展示。 PHP中不支持'g'。 'm'使'^ $'匹配每行,而不是整個字符串。 – chris85

4

你能想出如下:

<?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

+0

PHP不會在那裏解釋,你應該在問題的主體中自己做。 – chris85

+0

@ chris85,也許檢查'x'修飾符... – trincot

+0

@ chris85:[爲什麼不???](http://ideone.com/oMe3Qp) - 這正是'x'修飾符的用途。 – Jan

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

5

如果重音字母應該是允許的,或存在於任何其他信Unicode範圍(如希臘語或西里爾語讓TER值),然後使用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', 
), 
) 

NB:與\w的差是[\pL\d]將不匹配下劃線。