duanbi6522 2011-02-10 08:12
浏览 38
已采纳

PHP正则表达式括号内的精确数据

I have some string like Western Australia 223/5 (59.3 ov)

I would like to split this string and extract the following informations with regular expressions

$team = 'Western Australia'
$runs = 223/5
$overs = 59.3

Issue is, format of the text is varying, it may any of the follwing

  • Western Australia 223/5 (59.3 ov)
  • Australia 223/5 (59.3 ov)
  • KwaZulu-Natal Inland
  • Sri Lanka v West Indies

Any help (like is it possible to have in a single regexp) will be appreciated..

  • 写回答

2条回答 默认 最新

  • doudihuang7642 2011-02-10 08:27
    关注
    if (preg_match(
        '%^                 # start of string
        (?P<team>.*?)       # Any number of characters, as few as possible (--> team)
        (?:\s+              # Try to match the following group: whitespace plus...
         (?P<runs>\d+       # a string of the form number...
                  (?:/\d+)? # optionally followed by /number
         )                  # (--> runs)
        )?                  # optionally
        (?:\s+              # Try to match the following group: whitespace plus...
         \(                 # (
         (?P<overs>[\d.]+)  # a number (optionally decimal) (--> overs)
         \s+ov\)            # followed by ov)
        )?                  # optionally
        \s*                 # optional whitespace at the end
        $                   # end of string
        %six', 
        $subject, $regs)) {
        $team = $regs['team'];
        $runs = $regs['runs'];
        $overs = $regs['overs'];
    } else {
        $result = "";
    }
    

    You might need to catch an error if the matches <runs> and/or <overs> are not actually present in the string. I don't know much about PHP. (Don't know much biology...SCNR)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿