1

みんな。問題があり、解決できません。

パターン:\'(.*?)\'

ソース文字列:'abc', 'def', 'gh\'', 'ui'

[abc][def]、が必要[gh\']です[ui]

しかし、私は、、、など[abc]を取得します。[def][gh\][, ]

出来ますか?前もって感謝します

4

4 に答える 4

1

はい、それらの一致は可能です。

ただし、引用符内の内容を取得できるかどうかを確認する場合は、カンマで分割し (できれば CSV パーサーを使用)、末尾のスペースを削除するのが最も簡単です。

それ以外の場合は、次のようなものを試すことができます。

\'((?:\\\'|[^\'])+)\'

どちらかまたは引用符以外の文字に一致しますが、 ...\'のようなものに対しては失敗します\\'

この場合に使用できる長くて遅い正規表現は次のとおりです。

\'((?:(?<!\\)(?:\\\\)*\\\'|[^\'])+)\'

PHP の場合:

preg_match_all('/\'((?:(?<!\\)\\\'|[^\'])+)\'/', $text, $match);

または、二重引用符を使用する場合:

preg_match_all("/'((?:(?<!\\\)\\\'|[^'])+)'/", $text, $match);

(?<!\\)正常に動作するはずなのに、エラーが発生する理由がわかりません(実際には 1 つのリテラル バックスラッシュを意味します)。パターンを に変更すると機能し(?<!\\\\)ます。

イデオンデモ

編集:よりシンプルで、より優れた、より高速な正規表現を見つけました:

preg_match_all("/'((?:[^'\\]|\\.)+)'/", $text, $match);
于 2013-10-07T16:53:26.657 に答える
1

PHP コード: 否定後読みの使用

$s = "'abc', 'def', 'ghf\\\\', 'jkl\'f'";
echo "$s\n";
if (preg_match_all("~'.*?(?<!(?:(?<!\\\\)\\\\))'~", $s, $arr))
   var_dump($arr[0]);

アウトアウト:

array(4) {
  [0]=>
  string(5) "'abc'"
  [1]=>
  string(5) "'def'"
  [2]=>
  string(7) "'ghf\\'"
  [3]=>
  string(8) "'jkl\'f'"
}

ライブデモ: http://ideone.com/y80Gas

于 2013-10-07T17:10:18.853 に答える
0
<?php

    // string to extract data from 
    $string  = "'abc', 'def', 'gh\'', 'ui'";

    // make the string into an array with a comma as the delimiter 
    $strings = explode(",", $string);

    # OPTION 1: keep the '

        // or, if you want to keep that escaped single quote
        $replacee = ["'", " "];
        $strings  = str_replace($replacee, "", $strings);
        $strings  = str_replace("\\", "\'", $strings);


    # OPTION 2: remove the ' /// uncomment tripple slash

        // replace the single quotes, spaces, and the backslash 
        /// $replacee = ["'", "\\", " "];

        // do the replacement, the $replacee with an empty string
        /// $strings = str_replace($replacee, "", $strings);


    var_dump($strings);

?>
于 2013-10-07T18:04:25.607 に答える
-1

代わりに使用する必要がありますstr_getcsv

str_getcsv("'abc', 'def', 'gh\'', 'ui'", ",", "'");
于 2013-10-07T16:53:18.537 に答える