正则表达式 - 避免任何不必要的搜索 preg_match() PHP

Regex - avoid any unnecessary searches preg_match() PHP

你好,我的正则表达式有点问题。

对于简单的:

$pattern='/^(a([0-9]|[a-z])?|b(\=|\?)?)$/';
$subject='b=';

returns数组:

Array
(
[0] => b=
[1] => b=
[2] => 
[3] => =
)

此数组中的索引号 2 来自 a(...)? - 我的问题:我可以在我的结果中避免这个字段吗?我有很长的图案,我的阵列有 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]+)\))?)$/

此致

阅读您的模式后,我认为您可以使用此版本使其更简单:

\A([in][oh]?)([+-]|\(\+?[0-9]+;\+?[0-9]+\))\z

demo

请注意,我不确切知道您需要的捕获,但您可以根据需要添加它们。

详情:

\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