【问题标题】:Fetching the substring contained between two specific words获取包含在两个特定单词之间的子字符串
【发布时间】:2012-10-22 22:55:56
【问题描述】:

当我对使用 ruby​​ 的特定单词之间包含的文本感兴趣时,我想知道如何进行。 例如。

@var = "Hi, I want to extract container_start ONLY THIS DYNAMIC CONTENT container_end from the message contained between the container_start and container_end "

现在我想从字符串中提取大写的内容,即动态但始终包含在两个容器中(container_startcontainer_end

【问题讨论】:

  • 您使用的是哪种技术?
  • 谢谢,正在研究 ruby​​ on rails
  • 如果您查看 html 标签匹配器正则表达式,您可能会知道如何获取它。
  • stackoverflow.com/questions/4115115/…(修改它以满足您的需要)

标签: ruby regex ruby-on-rails-3 substring


【解决方案1】:

我只是想补充一些我从here得到的重要内容

@var = "Hi, I want to extract container_start \n\nONLY \nTHIS\n DYNAMIC\n CONTENT\n\n container_end from the message contained between the container_start and container_end "
@var[/container_start(.*?)container_end/m, 1]

除了:

/./ - Any character except a newline.
/./m - Any character (the m modifier enables multiline mode)

【讨论】:

    【解决方案2】:

    只是为了提供非正则表达式的答案,您还可以使用两个 .splits 来选择数组条目。

    => @var = "Hi, I want to extract container_start ONLY THIS DYNAMIC CONTENT container_end from the message contained between the container_start and container_end "
    => @var.split("container_start ")[1].split(" container_end")[0]
    => "ONLY THIS DYNAMIC CONTENT"
    

    .split 在引号中的文本处拆分字符串。 [1] 选择该文本之后的部分。对于第二次切割,您需要“container_end”之前的部分,因此您选择 [0]。

    您需要在两个 .split 子字符串中保留空格以删除前导和尾随空格。或者,使用 .lstrip 和 .rstrip。

    如果有更多“container_start”和“container_end”字符串,您需要调整数组选择器以在这两个子字符串之间选择正确的 @var 部分。

    【讨论】:

      【解决方案3】:

      使用 Victor 给出的相同正则表达式,您也可以这样做

      var.split(/container_start(.*?)container_end/)[1]
      

      【讨论】:

        【解决方案4】:

        简单的正则表达式就可以了:

        @var = "Hi, I want to extract container_start **ONLY THIS DYNAMIC CONTENT** container_end from the message contained between the container_start and container_end "
        @var[/container_start(.*?)container_end/, 1] # => " **ONLY THIS DYNAMIC CONTENT** "
        

        【讨论】:

        • 感谢您的回答,真是太棒了。
        • 如果我没有找到这篇文章(或类似的文章),我怎么会找到这个答案?这让我觉得这是一个不太直观的解决方案。只是好奇。
        • @victor-deryagin .. 我是新手,所以一个非常基本的问题,为什么 1 在正则表达式中使用,
        猜你喜欢
        • 1970-01-01
        • 2016-05-05
        • 1970-01-01
        • 2014-09-23
        • 1970-01-01
        • 1970-01-01
        • 2014-10-03
        • 2016-12-06
        • 2013-12-12
        相关资源
        最近更新 更多