首页 > 解决方案 > 仅在 perl 正则表达式中匹配最后一次出现

问题描述

/1.1/s/1/-/g

我正在做学校作业以参考实现 sed 命令。我得到这个字符串来匹配“/1/-/”。我有实验

$str =~ m{/[^/]*/[^/]*/}g;

但结果是/1.1/s/。我怎样才能只得到“/1/-/”有人可以帮我吗?

标签: regexperl

解决方案


利用

/[^/]*/[^/]*/(?=[^/]*$)

证明

解释

--------------------------------------------------------------------------------
  /                        '/'
--------------------------------------------------------------------------------
  [^/]*                    any character except: '/' (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  /                        '/'
--------------------------------------------------------------------------------
  [^/]*                    any character except: '/' (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  /                        '/'
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    [^/]*                    any character except: '/' (0 or more
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    $                        before an optional \n, and the end of
                             the string
--------------------------------------------------------------------------------
  )                        end of look-ahead

推荐阅读