2011-02-12 113 views
1

我有幾行需要更新,其中雙撇號在某些位置被替換,並且被刪除而不是其他位置。正則表達式並用preg_replace替換雙撇號

所以:

(2, 'Name 2', '', 8, 0, 0, 1, 'Info blah blah', 0, 4), 
(3, 'Name 3', 'A normal bit of information', 8, 1, 0, 1, 'Info more blah', 0, 4), 
(45, 'Name 45', 'Info with '' in it like it''s stuff', 356, 10, 1, 1, '', 0, 9) 

需求,成爲:

(2, 'Name 2', '', 8, 0, 0, 1, 'Info blah blah', 0, 4), 
(3, 'Name 3', 'A normal bit of information', 8, 1, 0, 1, 'Info more blah', 0, 4), 
(45, 'Name 45', 'Info with \'\' in it like it\'\'s stuff', 356, 10, 1, 1, '', 0, 9) 

在嘗試各種方法,我管理 '與\' 更新所有 '\',然後打破以後使用的功能。

+0

哪裏撇號?我所看到的都是單獨的字符。 – sln 2011-02-13 00:14:44

回答

1

呃,這真的需要一些解析。如果您使用正則表達式,它只會在最佳賭注的基礎上工作。

如果您可以認爲'',始終是CSV列表中的空字符串,則可以選擇查找逗號。如果其中一個字符串但是包含逗號後的雙引號,那麼這是要失敗的:

preg_replace("/''(?![,)])/", "\\'\\'", $text); 

要增加一些安全性,您可以添加一個前綴檢查像(?<=[(\s]) - 但是,這有助於只有很少的。

+0

工作完美,因爲它修復了所有''。我注意到文件中有幾個點有三個''',但我可以手動處理這些點。謝謝! – Sara 2011-02-12 23:50:36

+0

字符串既不包含**,**也不包含單引號,否則其在此上下文中不可解析。但即使沒有這樣的考慮,你們在很多層面上都失敗了。它必須考慮開始和結束的分隔符,而不是在''之後,否則它會失敗。 – sln 2011-02-12 23:56:50

1
'(([^']*?)('{2})([^']*?))+'([,|\)])

這應該能夠通過'$1\'\'$4'$5被替換,儘管如果在文字之後出現一個逗號將匹配單引號內只有2單引號。

1

s/(?<=')([^',]*)''(?=[^',]*')/$1\\'\\'/g

記住,你以後不能改變遊戲,並允許定界符之間的單引號「(」)」,因爲不與compatable‘(’‘)’。好?

use strict; 
use warnings; 

my @data = (
"(2, 'Name 2', '', 8, 0, 0, 1, 'Info blah blah', 0, 4), ", 
"(3, 'Name 3', 'A normal bit of information', 8, 1, 0, 1, 'Info more blah', 0, 4),", 
"(45, 'Name 45', 'Info with '' in it like it''s stuff', 356, 10, 1, 1, '', 0, 9)", 
"''''' ','''',''''", 
); 

for (@data) { 
    print "\n$_\n"; 
    if (
      s/ (?<=')([^',]*) '' (?= [^',]*')/$1\\'\\'/xg 
     ) 
    { 
     print "==>\t$_\n"; 
    } 
} 

輸出:
(2, 'Name 2', '', 8, 0, 0, 1, 'Info blah blah', 0, 4),
(3, 'Name 3', 'A normal bit of information', 8, 1, 0, 1, 'Info more blah', 0, 4),
(45, 'Name 45', 'Info with '' in it like it''s stuff', 356, 10, 1, 1, '', 0, 9)
==> (45, 'Name 45', 'Info with \'\' in it like it\'\'s stuff', 356, 10, 1, 1, '', 0, 9)
''''' ','''',''''
==> '\'\'\'\' ','\'\'','\'\''