在substring1之后和substring2之前获取字符串

时间:2017-07-01 15:18:48

标签: ruby

假设我有以下字符串:

Lorem Ipsum(tag1) is simply dummy text of(tag2) the printing and typesetting industry

我想得到tag1和tag2之间的子串,因此

is simply dummy text of

我怎么能用Ruby做到这一点?

5 个答案:

答案 0 :(得分:1)

试试这个:

str = "Lorem Ipsum(tag1) is simply dummy text of(tag2) the printing and typesetting industry"


str[/\(tag1\)(.*?)\(tag2\)/m, 1]
# => " is simply dummy text of"

答案 1 :(得分:1)

尝试String#split

str = "Lorem Ipsum(tag1) is simply dummy text of(tag2) the printing and typesetting industry"
str.split(/\(tag2\)|\(tag1\)/)[1]
#=>"is simply dummy text of"

答案 2 :(得分:1)

您可以使用REGEX的capturing technique。让我解释一下:

> str = "Lorem Ipsum(tag1) is simply dummy text of(tag2) the printing and typesetting industry"

> a = str.match /\(tag1\)(.*)\(tag2\)/
=> #<MatchData "(tag1) is simply dummy text of(tag2)" 1:" is simply dummy text of">

> a[1]
=> " is simply dummy text of"

在这里,我使用\(\)转义字符串中的括号,因为REGEX引擎可能会因为它具有特殊含义而感到困惑。

接下来,(.*)引用capture所有长度为any的字符。 任何都由*(Asterisk)隐含。

一般情况下,它会匹配你所拥有的两个单词之间的所有字符作为开始&amp;终点。

答案 3 :(得分:1)

非正则表达式解决方案:

str = "Lorem Ipsum(tag1) is simply dummy text of(tag2) the printing industry"

str[str.index("(tag1)")+6..str.index("(tag2)")-1]
  #=> " is simply dummy text of"

答案 4 :(得分:0)

您可以使用lookbehind和lookahead并在以下文本之间捕获文本:

> st='Lorem Ipsum(tag1) is simply dummy text of(tag2) the printing and typesetting industry'
> st[/(?<=tag\d\) ).*?(?=\(tag\d)/]
=> "is simply dummy text of"