【问题标题】:Explanation of a regex正则表达式的解释
【发布时间】:2014-02-14 10:52:12
【问题描述】:

下面的正则表达式是什么意思?

fspec="/exp/home1/abc.txt"
fname="${fspec##*/}"

我知道它是做什么的,但不知道它是怎么做的?我不清楚获取 fname。

请解释一下。

【问题讨论】:

  • @TimPietzcker,不,但可以原谅提问者认为它是一个。参考 shruti,可以在 string manipulation 的 bash 手册页中找到解释。

标签: regex bash shell


【解决方案1】:

${var##*/} 语法将所有内容剥离到最后一个 /

$ fspec="/exp/home1/abc.txt"
$ echo "${fspec##*/}"
abc.txt

一般来说,${string##substring} 会从$string 的前面去除$substring 的最长匹配项。

如需进一步参考,您可以查看Bash String Manipulation 的多个解释和示例。

【讨论】:

    【解决方案2】:

    以下是 bash 文档的解释。

    ${parameter#word}
    ${parameter##word}
    The  word  is  expanded  to  produce  a pattern just as in pathname
    expansion.  If the pattern matches the beginning of  the  value  of
    parameter,  then  the result of the expansion is the expanded value
    of parameter with the shortest matching pattern (the ``#'' case) or
    the longest matching pattern (the ``##'' case) deleted.  
    

    根据上述解释,在您的示例中,word=*/ 表示零(或)任意数量的以 / 结尾的字符。

    bash-3.2$fspec="/exp/home1/abc.txt"
    bash-3.2$echo "${fspec##*/}"   # Here it deletes the longest matching pattern
    # (i.e) /exp/home1/
    # Output is abc.txt
    
    bash-3.2$echo "${fspec#*/}"    # Here it deletes the shortest matching patter
    #(i.e) /
    # Output is exp/home1/abc.txt
    bash-3.2$
    

    【讨论】:

      猜你喜欢
      • 2013-01-06
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多