引号之间的文本的正则表达式是什么?

时间:2011-08-11 09:47:19

标签: php regex

好的,我试过看其他答案,但无法解决我的问题。所以这是代码:

{"chg":"-0.71","vol":"40700","time":"11.08.2011 12:29:09","high":"1.417","low":"1.360","last":"1.400","pcl":"1.410","turnover":"56,560.25"}

我需要在引号中获取每秒值(因为"name"值是常量)。我实际上已经知道我需要在:""之间获取文本,但我无法为此编写正则表达式。

编辑:我在php中正在做preg_match_all。它位于:""之间,而不是其他人编辑过的""

2 个答案:

答案 0 :(得分:7)

为什么在 earth 上你会尝试用正则表达式解析JSON? PHP已经parses JSON 正确内置功能。

代码:

<?php
$input = '{"chg":"-0.71","vol":"40700","time":"11.08.2011 12:29:09","high":"1.417","low":"1.360","last":"1.400","pcl":"1.410","turnover":"56,560.25"}';
print_r(json_decode($input, true));
?>

输出:

Array
(
    [chg] => -0.71
    [vol] => 40700
    [time] => 11.08.2011 12:29:09
    [high] => 1.417
    [low] => 1.360
    [last] => 1.400
    [pcl] => 1.410
    [turnover] => 56,560.25
)

Live demo.

答案 1 :(得分:-1)

根据您的语言,您可能需要转义字符或在正面或背面添加正斜杠。但它基本上是:

:"([^"].*?)"

/:"([^"].*?)"/

我在groovy中测试了这个,如下所示,它可以工作。

import java.util.regex.*;

String test='{"chg":"-0.71","vol":"40700","time":"11.08.2011 12:29:09","high":"1.417","low":"1.360","last":"1.400","pcl":"1.410","turnover":"56,560.25"}'

  // Create a pattern to match breaks
  Pattern p = Pattern.compile(':"([^"]*)"');
  // Split input with the pattern
  // Run some matches
  Matcher m = p.matcher(test);
  while (m.find())
      System.out.println("Found comment: "+m.group().replace('"','').replace(":",""));

输出是:

Found comment: -0.71
Found comment: 40700
Found comment: 11.08.2011 12:29:09
Found comment: 1.417
Found comment: 1.360
Found comment: 1.400
Found comment: 1.410
Found comment: 56,560.25

PHP示例

<?php
$subject = '{"chg":"-0.71","vol":"40700","time":"11.08.2011 12:29:09","high":"1.417","low":"1.360","last":"1.400","pcl":"1.410","turnover":"56,560.25"}';
$pattern = '/(?<=:")[^"]*/';
preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

输出为:

Array ( [0] => Array ( [0] => Array ( [0] => -0.71 [1] => 8 ) [1] => Array ( [0] => 40700 [1] => 22 ) [2] => Array ( [0] => 11.08.2011 12:29:09 [1] => 37 ) [3] => Array ( [0] => 1.417 [1] => 66 ) [4] => Array ( [0] => 1.360 [1] => 80 ) [5] => Array ( [0] => 1.400 [1] => 95 ) [6] => Array ( [0] => 1.410 [1] => 109 ) [7] => Array ( [0] => 56,560.25 [1] => 128 ) ) )