2016-08-18 107 views
1

我需要創建laravel遷移,所以我已經使用Sublime Text中的正則表達式使用「替換文件」將我的SQL腳本轉換爲laravel遷移格式。嵌套正則表達式替換

我的問題是,我有由「表名」在約70桌以下字符串替換「@」字符:

Schema::table('tablename', function($table) { 
     $table->dropForeign('@_columnname_foreign'); 
}); 

其實我可以使用下面的表達式做到這一點:

(Schema::table\('([a-z]+)',[\s]*function\(\$table\)[\s]*{[\s]*\$table->dropForeign\(')@(_[a-z_]+'\);) 

而在替代領域:

$1$2$3 

,但我不知道該怎麼辦時,該表有一個以上的FK:

Schema::table('tablename1', function($table) { 
    $table->dropForeign('@_field1_foreign'); 
    $table->dropForeign('@_field2_foreign'); 
    $table->dropForeign('@_field3_foreign'); 
    $table->dropForeign('@_field4_foreign'); 
    $table->dropForeign('@_field5_foreign'); 
    $table->dropForeign('@_field6_foreign'); 
}); 

我一直在使用這個網站來驗證我的正則表達式RegExr

+0

@revo,我只是確保:SublimeTex2和SublimeText3正則表達式實現之間有區別。刪除我的評論。 –

+0

這很奇怪。去除地雷。 @WiktorStribiżew – revo

回答

1

這不是在崇高的文本正則表達式一件容易的事。使用正則表達式的唯一方法是確保使用可選數量的table-dropForeign行(匹配的延遲)捕獲函數單數,並在下一行替換@

正則表達式如下需要單擊直到所有比賽都發現所有多次更換。

(Schema::table\('([a-z0-9]+)',\s*function\(\$table\)\s*{(?:\s*\$table->dropForeign\('[a-z0-9]+_\w+'\);)*?\s*\$table->dropForeign\(')@(_\w+'\);) 

替換爲$1$2$3。請參閱this regex demo,您可以在其中手動替換第二個塊中的@,並查看匹配的進一步方式。

詳細

  • (Schema::table\('([a-z0-9]+)',\s*function\(\$table\)\s*{(?:\s*\$table->dropForeign\('[a-z0-9]+_\w+'\);)*?\s*\$table->dropForeign\(') - 第1組捕獲:
    • Schema::table\(' - 字面Schema::table('
    • ([a-z0-9]+) - 第2組捕獲1+字母數字(不檢查區分大小寫選項以匹配大寫的ASCII字母)
    • ',\s* - 逗號和0+空格
    • function\(\$table\) - 一個文字文本function($table)
    • \s* - 0+空格
    • { - 字面{(在SublimeText 2,它需要轉義)
    • (?:\s*\$table->dropForeign\('[a-z0-9]+_\w+'\);)*? - 0+序列,但儘可能少,匹配:
      • \s*\$table->dropForeign\(' - 0+ whitespaces然後文字文本`$ table-> dropForeign('
      • [a-z0-9]+_\w+ - 1+字母數字,_和1+數字,字母或下劃線(\w+
      • '\); - 文字串');
    • \s* - 0+空格
    • \$table->dropForeign\(' - 一個文字文本$table->dropForeign('
  • @ - 與b匹配的@符號È取代
  • (_\w+'\);) - 組2捕獲:
    • _ - 下劃線
    • \w+ - 1或多個字母,數字或下劃線
    • '\); - 文字串');

enter image description here

注意:我認爲我發現的問題與導致在Sublime Text 2中出現正則表達式失敗的未轉義的{有關。在Sublime Text 3中,正則表達式中的{不必轉義。

+0

好吧,這比複製和粘貼約70個表定義更好! :) 謝謝! – UselesssCat