From: Jesse B. on
trying to do something like this

some text
some more text /what I want/ some more text
some more text

returns

"what I want"

how would I write this to get just what is between the first and second
forward slashes?

also I might want to use several times within the same file.

thanks in advance.
--
Posted via http://www.ruby-forum.com/.

From: Caleb Clausen on
On 4/9/10, Jesse B. <jessebos(a)aol.com> wrote:
> trying to do something like this
>
> some text
> some more text /what I want/ some more text
> some more text
>
> returns
>
> "what I want"
>
> how would I write this to get just what is between the first and second
> forward slashes?

irb(main):001:0> s=<<END
irb(main):002:0" some text
irb(main):003:0" some more text /what I want/ some more text
irb(main):004:0" some more text
irb(main):005:0" END
=> "some text\nsome more text /what I want/ some more text\nsome more text\n"
irb(main):006:0> s[%r{/.*?/}]
=> "/what I want/"

> also I might want to use several times within the same file.

irb(main):007:0> s<<<<END2
irb(main):008:0" yet some more text
irb(main):009:0" blab blab /what I want even more/ and after that
irb(main):010:0" yaddidda yaddidda
irb(main):011:0" END2
=> "some text\nsome more text /what I want/ some more text\nsome more
text\nyet some more text\nblab blab /what I want even more/ and after
that\nyaddidda yaddidda\n"
irb(main):012:0> s.scan %r{/.*?/}
=> ["/what I want/", "/what I want even more/"]


HTH

From: Robert Klemme on
On 04/09/2010 10:26 PM, Caleb Clausen wrote:
> On 4/9/10, Jesse B. <jessebos(a)aol.com> wrote:
>> trying to do something like this
>>
>> some text
>> some more text /what I want/ some more text
>> some more text
>>
>> returns
>>
>> "what I want"
>>
>> how would I write this to get just what is between the first and second
>> forward slashes?
>
> irb(main):001:0> s=<<END
> irb(main):002:0" some text
> irb(main):003:0" some more text /what I want/ some more text
> irb(main):004:0" some more text
> irb(main):005:0" END
> => "some text\nsome more text /what I want/ some more text\nsome more text\n"
> irb(main):006:0> s[%r{/.*?/}]
> => "/what I want/"

With a capturing group you can even get exactly the text wanted:

irb(main):001:0> s = "some /text that I want/ not"
=> "some /text that I want/ not"
irb(main):002:0> s[%r{/(.*?)/}, 1]
=> "text that I want"

Or, if you also want to remove whitespace at the edges:

irb(main):004:0> s = "some / text that I want trimmed / not"
=> "some / text that I want trimmed / not"
irb(main):005:0> s[%r{/(.*?)/}, 1]
=> " text that I want trimmed "
irb(main):006:0> s[%r{/\s*(.*?)\s*/}, 1]
=> "text that I want trimmed"

Kind regards

robert

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/