【问题标题】:How to extract substring from string如何从字符串中提取子字符串
【发布时间】:2011-11-17 08:28:56
【问题描述】:

我有一个字符串,它看起来并不总是一样,如果它存在,我想从这个字符串中提取一些信息。该字符串可能类似于以下内容之一:

myCommand -s 12 moreParameters
myCommand -s12 moreParamaters
myCommand -s moreParameters

我想得到这个数字,在这种情况下是 12,如果它存在的话。我怎样才能做到这一点?

非常感谢!

编辑:字符串有第四个可能的值:

myCommand moreParameters

如何修改正则表达式以涵盖这种情况?

【问题讨论】:

    标签: bash sed grep substring extract


    【解决方案1】:
    $ a="myCommand -s 12 moreParameters"
    $ b="myCommand -s12 moreParamaters"
    $ echo $(expr "$a" : '[^0-9]*\([0-9]*\)')
    12
    $ echo $(expr "$b" : '[^0-9]*\([0-9]*\)')
    12
    

    【讨论】:

      【解决方案2】:

      试试这个:

      n=$(echo "$string"|sed 's/^.*-s *\([0-9]*\).*$/\1/')
      

      这将匹配一个-s,最后是空格和数字;并用数字替换整个字符串。

      myCommand -s 12 moreParameters => 12
      myCommand -s12 moreParamaters  => 12
      myCommand -s moreParameters    => 空字符串

      编辑:字符串有第四个可能的值:

      myCommand moreParameters

      如何修改正则表达式以涵盖这种情况?

      【讨论】:

      • 非常感谢您的快速回复。非常感谢!
      • 在 bash 中,您可以使用“here-strings”:n=$(sed 's/^.*-s *\([0-9]*\).*$/\1/' <<< "$string")
      • 您可以处理其他情况,例如通过仅打印匹配行。 sed -n 's/^.*-s *\([0-9]*\).*$/\1/p'
      【解决方案3】:

      您可以在不需要外部工具的情况下完成所有这些操作

      $ shopt -s extglob
      $ string="myCommand -s 12 moreParameters"
      $ string="${string##*-s+( )}"
      $ echo "${string%% *}"
      12
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-24
        • 2011-07-21
        • 1970-01-01
        • 2023-04-03
        • 2018-09-29
        • 2021-12-23
        相关资源
        最近更新 更多