2011-02-12 52 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)
''''' ','''',''''
==> '\'\'\'\' ','\'\'','\'\''