2010-12-08 39 views
2


我想知道,我的字符串應該有什麼正則表達式。我的字符串只能包含「|」和數字。
例如:「111 | 333 | 111 | 333」。字符串必須從數字開始。我正在使用此代碼,但他很醜:php正則表達式適用於「|」和數字

if (!preg_match('/\|d/', $ids)) { 
    $this->_redirect(ROOT_PATH . '/commission/payment/active'); 
} 

在此先感謝您。對不起我的英語不好。

回答

3

看看你的例子,我假設你正在尋找一個匹配字符串的開始和結束與數字和數字是用|分開的正則表達式。如果是這樣你可以使用:

^\d+(?:\|\d+)*$ 

說明:

^  - Start anchor. 
\d+ - One ore more digits, that is a number. 
(? ) - Used for grouping. 
\| - | is a regex meta char used for alternation, 
     to match a literal pipe, escape it. 
    * - Quantifier for zero or more. 
$  - End anchor. 
2

的正則表達式是:

^\d[|\d]*$ 

^ - Start matching only from the beginning of the string 
\d - Match a digit 
[] - Define a class of possible matches. Match any of the following cases: 
    | - (inside a character class) Match the '|' character 
    \d - Match a digit 
$ - End matching only from the beginning of the string 

注:擺脫|是不是在這種情況下,必要的。

+0

我知道OP並沒有真正指定它,但是這也可以允許像`123 || 456 |`這樣的序列(最後雙管和管道)。 – 2010-12-08 10:13:28

1

僅包含|或數字並以數字開頭的字符串被寫爲^\d(\||\d)*$。這意味着:要麼\|(注意逃跑!)或一個數字,寫作\d,多次。

^$意思是:從開始到結束,即在其之前或之後沒有其他字符。

1

我認爲/^\d[\d\|]*$/會工作,但是,如果你總是有三個數字分隔的酒吧,你需要/^\d{3}(?:\|\d{3})*$/

編輯: 最後,如果您始終有一個或多個數字的序列由條分隔,則會執行:/^\d+(?:\|\d+)*$/