我想知道,我的字符串应该有什么正则表达式。我的字符串只能包含“|”和数字。
例如:“111 | 333 | 111 | 333”。字符串必须从数字开始。我正在使用此代码,但他很丑:php正则表达式适用于“|”和数字
if (!preg_match('/\|d/', $ids)) {
$this->_redirect(ROOT_PATH . '/commission/payment/active');
}
在此先感谢您。对不起我的英语不好。
我想知道,我的字符串应该有什么正则表达式。我的字符串只能包含“|”和数字。
例如:“111 | 333 | 111 | 333”。字符串必须从数字开始。我正在使用此代码,但他很丑:php正则表达式适用于“|”和数字
if (!preg_match('/\|d/', $ids)) {
$this->_redirect(ROOT_PATH . '/commission/payment/active');
}
在此先感谢您。对不起我的英语不好。
看看你的例子,我假设你正在寻找一个匹配字符串的开始和结束与数字和数字是用|
分开的正则表达式。如果是这样你可以使用:
^\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.
的正则表达式是:
^\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
注:摆脱|
是不是在这种情况下,必要的。
仅包含|
或数字并以数字开头的字符串被写为^\d(\||\d)*$
。这意味着:要么\|
(注意逃跑!)或一个数字,写作\d
,多次。
^
和$
意思是:从开始到结束,即在其之前或之后没有其他字符。
我认为/^\d[\d\|]*$/
会工作,但是,如果你总是有三个数字分隔的酒吧,你需要/^\d{3}(?:\|\d{3})*$/
。
编辑: 最后,如果您始终有一个或多个数字的序列由条分隔,则会执行:/^\d+(?:\|\d+)*$/
。
我知道OP并没有真正指定它,但是这也可以允许像`123 || 456 |`这样的序列(最后双管和管道)。 – 2010-12-08 10:13:28