您好,我的正则表达式存在小问题。
简单来说:
$pattern='/^(a([0-9]|[a-z])?|b(\=|\?)?)$/';
$subject='b=';
返回数组:
Array
(
[0] => b=
[1] => b=
[2] =>
[3] => =
)
此数组中的索引号2来自(...)? - 我的问题:我可以在结果中避免使用此字段吗?我有很长的模式,我的数组是90%空。我可以用一些魔法字符删除这些空字段吗?
编辑: 在我的模式中我有类似的东西:
n(o|h)?(\+|\-|\(([+]?[0-9]+);([+]?[0-9]+)\))?
它将搜索字符串,如no +或n(12; 15)。我可以更简单吗?而且我有更多这样的文字,这意味着我有类似的东西:
/^(n(o|h)?(\+|\-|\(([+]?[0-9]+);([+]?[0-9]+)\))?|i(o|h)?(\+|\-|\(([+]?[0-9]+);([+]?[0-9]+)\))?)$/
此致
答案 0 :(得分:1)
阅读完模式之后,我认为您可以使用此版本更简单:
\A([in][oh]?)([+-]|\(\+?[0-9]+;\+?[0-9]+\))\z
请注意,我并不确切知道您需要的捕捉,但您可以根据需要添加它们。
细节:
\A # anchor for the start of the string
( # capture group 1:
[in] # a 'i' or a 'n'
[oh]? # a 'o' or a 'h' (optional)
)
( # capture group 2:
[+-] # a '+' or a '-'
| # OR
\(\+?[0-9]+;\+?[0-9]+\)
)
\z # anchor for the end of the string