みんな。問題があり、解決できません。
パターン:\'(.*?)\'
ソース文字列:'abc', 'def', 'gh\'', 'ui'
[abc]
、[def]
、が必要[gh\']
です[ui]
しかし、私は、、、など[abc]
を取得します。[def]
[gh\]
[, ]
出来ますか?前もって感謝します
はい、それらの一致は可能です。
ただし、引用符内の内容を取得できるかどうかを確認する場合は、カンマで分割し (できれば CSV パーサーを使用)、末尾のスペースを削除するのが最も簡単です。
それ以外の場合は、次のようなものを試すことができます。
\'((?:\\\'|[^\'])+)\'
どちらかまたは引用符以外の文字に一致しますが、 ...\'
のようなものに対しては失敗します\\'
この場合に使用できる長くて遅い正規表現は次のとおりです。
\'((?:(?<!\\)(?:\\\\)*\\\'|[^\'])+)\'
PHP の場合:
preg_match_all('/\'((?:(?<!\\)\\\'|[^\'])+)\'/', $text, $match);
または、二重引用符を使用する場合:
preg_match_all("/'((?:(?<!\\\)\\\'|[^'])+)'/", $text, $match);
(?<!\\)
正常に動作するはずなのに、エラーが発生する理由がわかりません(実際には 1 つのリテラル バックスラッシュを意味します)。パターンを に変更すると機能し(?<!\\\\)
ます。
preg_match_all("/'((?:[^'\\]|\\.)+)'/", $text, $match);
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'"
}
<?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);
?>
代わりに使用する必要がありますstr_getcsv
str_getcsv("'abc', 'def', 'gh\'', 'ui'", ",", "'");