PHP正则表达式的具体报价
问题描述:
我有一些极端的无法理解我怎么只能得到字符的双引号内时,我只希望它得到字符时,它是这样的:PHP正则表达式的具体报价
Item.name = "thisCouldBeAnything"
当可以是解析器中的其他双引号。我很难理解正则表达式是什么。
答
基于您的评论我需要它究竟是Item.name = ""
它不能只是搜索双引号。假设你想捕捉什么在双引号:
preg_match_all('/Item.name = "(.*)"/', $string, $matches);
或者,如果双引号内的值不应包含双引号:
preg_match_all('/Item.name = "([^"]+)"/', $string, $matches);
还是捕捉到这一切:
preg_match_all('/(Item.name = ".*")/', $string, $matches);
答
这是说:
全部
或者(劫持@Dmitry's example):
([\"\'])(.*?(?<!\\))\1
这是说:
([\"\']) # capture ' or " into group 1
( # second group
.*? # anything lazily
(?<!\\) # neg. lookbehind, make sure there's no backslash
)
\1 # the formerly captured string literal of group 1
注意,你不需要逃避方括号([...]
),但StackOverflow的渲染使得否则它很丑陋的字符串文字。
全部
PHP
片段(注意所谓的“价值”的[不必要]组和双反斜线转义):
<?php
$string = <<<DATA
Item.name = "thisCouldBeAnything"
Item.name = "thisCouldBe\"Any\"thing"
Item.name = 'thisCouldBeAnything'
Item.name = 'thisCouldBe\'Any\'"thing'
DATA;
$regex = '~(["\'])(?P<value>.*?(?<!\\\\))\1~';
preg_match_all($regex, $string, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
echo $match["value"] . "\n";
}
?>
+0
嘿这个作品除了下面的数据也作为Item.value Item.ID等进来,我不好意思在原始帖子上提及; /但我不想像Item.Desc等东西等 –
你的意思是它可能是“”这个“可能”是任何东西“,或者你是指其他地方的双引号?你需要更多的细节在你的问题,如输入,应该/不应该匹配等 – AbraCadaver
我的不好,我需要它正是Item.name =“”它不能只搜索双引号。 –