drxvjnx58751 2017-02-07 08:14
浏览 9
已采纳

正则表达式在一场比赛中获得所有比赛

I'm searching for a regex that matches all words, but will give only one match.

What I have:


Regex: (.*\={1})\d+(\D*)

Input: max. Money (EU)=600000 Euro

Output: Euro


This works fine, but it's possible that the Input is like this: max. Money (EU)=600000 Euro plus 20000 for one person.

Before the = could be anything, the only thing that I know is that the = is fixed. So every input have this.

So I'm searching for a regex that will give me for this input this output: Euro plus for one person.

I tried to use a regex like (\D+), but I'll get for this input 3 matches. Does someone know how to get all occurences in one match?

  • 写回答

1条回答 默认 最新

  • doulu8847 2017-02-07 08:26
    关注

    One cannot match discontinuous text with 1 match operation.

    The easiest workaround is to capture the whole substring after = + number, and then remove numbers from the match with preg_replace('~\s*\d+~', '', $m[1]).

    See the PHP demo:

    $re = '/=\d+\s*(.*)/';
    $str = 'max. Money (EU)=600000 Euro plus 20000 for one person';
    $res = '';
    if (preg_match($re, $str, $m)) {
        $res = preg_replace('~\s*\d+~', '', $m[1]);
    }
    echo $res; // => Euro plus for one person
    

    Since you mention that a = does not have to be followed by 1+ digits, you may really just explode the string at the first = and then remove digits in the second item:

    $chunks = explode("=", $str, 2);
    if (count($chunks) == 2) {
        $res = preg_replace('~\s*\d+~', '', $chunks[1]);
    }
    

    See this PHP demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?