正则表达式查找关键字

时间:2017-02-24 21:31:39

标签: php regex preg-match preg-match-all

我正在尝试捕获文本中的数字,后面跟着一个关键字'金额'

preg_match_all("/amount.+\b(\d+(\.\d+)?)/im", $input_lines, $output_array);

我的输入数据是

here is some number 100.25
that does not 200.
but this amount should be captured 300.
and this amount should be captured 400.25 too
and this amount should be captured $5023 too
and this amount should be captured $60.25 too
and this amount should be captured 700.25.

But not this amount 800.25.2

因此只应捕获数字300,400.25,5023,60.25,700.25

3 个答案:

答案 0 :(得分:2)

您正在寻找的正则表达式是:amount\D+(\d+(?:\.\d+)?)\.?(?!\d)

在此处查看此行动:https://regex101.com/r/iXwM40/1

这取决于“金额”这个词与数字集之间没有数字。

关键是最后一组括号,称为否定先行:(?!\d)如果后面的字符是数字,则不匹配。 \d

在此处查看有关前瞻的更多信息:http://www.regular-expressions.info/lookaround.html

答案 1 :(得分:1)

使用以下方法:

$input_lines = "here is some number 100.25
that does not 200.
but this amount should be captured 300.
and this amount should be captured 400.25 too
and this amount should be captured $5023 too
and this amount should be captured $60.25 too
and this amount should be captured 700.25.

But not this amount 800.25.2";

preg_match_all("/(?:amount [^\d]+?)\K\d+(\.\d+)?/m", $input_lines, $matches);

print_r($matches[0]);

输出: 阵列

(
    [0] => 300
    [1] => 400.25
    [2] => 5023
    [3] => 60.25
    [4] => 700.25
)

(?:amount [^\d]+?) - 将字符串(行)与amount匹配,后跟除数字之外的任何字符

\K - 重置报告的匹配的起点。任何先前消费的字符不再包含在最终匹配中

\d+(\.\d+)? - 匹配所需的数字(包括小数部分,如果是浮点数)

答案 2 :(得分:0)

尝试 \b amount \b .*? ( # (1 start) \d+ (?: \. \d* )? | \. \d+ ) # (1 end)

private void MakePng()
{
    string args = "-o" + graphPath + " -Tpng  " + dotPath;

    using(Process process = new Process())
    {
        ProcessStartInfo info = new ProcessStartInfo();
        info.FileName = VizGraphPath;
        info.Arguments = args;
        info.UseShellExecute = false;
        info.CreateNoWindow = true;

        process.StartInfo = info;
        process.EnableRaisingEvents = true;
        process.Start();
        process.WaitForExit(10*1000); //10 seconds
    }

    UpdateCanvas();
}