0

次の文字列から、以下のような配列を構築する正規表現を考え出そうとしています

$str = 'Hello world [something here]{optional}{optional}{optional}{n possibilities of this}';

これまでのところ、/^(\*{0,3})(.+)\[(.*)\]((?:{[a-z ]+})?)$/

Array
(
    [0] => Array
        (
            [0] => Hello world [something here]{optional}{optional}{optional}{n possibilities of this}
            [1] => 
            [2] => Hello world
            [3] => something here
            [4] => {optional}
            [5] => {optional}
            [6] => {optional}
            [7] => ...
            [8] => ...
            [9] => {n of this}
        )
)

これにはどのようなアプローチが良いでしょうか?ありがとう

4

2 に答える 2

0

I think you will need two steps for this.

  1. (.+)\[(.+)\](.+) will get you Hello world, something here, and {optional}...{optional}.

  2. Applying \{(.+?)\} to the last element from the previous step will get you optional params.

于 2010-05-03T20:44:00.297 に答える
0

これは、あなたが求めたよりもさらにクリーンであると私が信じているアプローチです。

コード: ( PHP デモ) (パターンデモ)

$str = 'Hello world [something here]{optional}{optional}{optional}{n possibilities of this}';

var_export(preg_split('/ *\[|\]|(?=\{)/', $str, 0, PREG_SPLIT_NO_EMPTY));

出力:

array (
  0 => 'Hello world',
  1 => 'something here',
  2 => '{optional}',
  3 => '{optional}',
  4 => '{optional}',
  5 => '{n possibilities of this}',
)

preg_split()可能性のある3回の発生で文字列が壊れます(プロセスでこれらの発生を削除します):

  • *\[0 個以上のスペースの後に左角括弧が続くことを意味します。
  • \]閉じ角括弧を意味します。
  • ?=\{)長さゼロの文字 (直前の位置...) を意味します。

*私のパターンは と の間に空の要素を生成し]ます{。この無駄な要素を排除するためPREG_SPLIT_NO_EMPTYに、関数呼び出しにフラグを追加しました。

于 2017-10-26T04:28:18.920 に答える