php正则表达式为“|”和数字

时间:2010-12-08 09:51:25

标签: php regex

我想知道,我的字符串应该有什么正则表达式。我的字符串只能包含“|”和数字。
例如:“111 | 333 | 111 | 333”。字符串必须从数字开始。我正在使用这段代码,但他很难看:

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

提前谢谢你。抱歉我的英文。

4 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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

注意:在这种情况下,无需转义|

答案 2 :(得分:1)

仅包含|或数字并以数字开头的字符串写为^\d(\||\d)*$。这意味着:\|(注意逃避!)或数字,写作\d,多次。

^$表示:从开始到结束,即之前或之后没有其他字符。

答案 3 :(得分:1)

我认为/^\d[\d\|]*$/可行,但是,如果您总是有三个数字用条形分隔,则需要/^\d{3}(?:\|\d{3})*$/

编辑: 最后,如果您始终将一个或多个数字的序列用条形分隔,则会执行以下操作:/^\d+(?:\|\d+)*$/