簡體   English   中英

正則表達式並用preg_replace代替雙撇號

[英]Regex and replacing double apostrophes with 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)

當嘗試各種方法時,我設法用\\'\\'更新所有'',然后中斷以后使用的功能。

嗯,這確實需要一些解析。 如果您使用正則表達式,那么它實際上只會在最佳選擇的基礎上起作用。

如果可以假設CSV列表中的空字符串始終是'',那么可以選擇逗號。 但是,如果其中一個字符串在雙引號后包含逗號,則此操作將失敗:

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

為了增加安全性,您可以添加前綴檢查,如(?<=[(\\s]) --但這僅能起到很小的作用。

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

這應該可以用'$1\\'\\'$4'$5代替,並且即使在字面量后面出現逗號,也只能匹配兩個單引號。

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

請記住,您以后不能更改游戲並不能在定界符'(')'之間使用單個撇號,因為這與'(')'不兼容。 好?

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)
''''' ','''',''''
==> '\\'\\'\\'\\' ','\\'\\'','\\'\\''

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM