Return string within seperators only

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.

On 4/9/10, Jesse B. [email protected] wrote:

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

On 04/09/2010 10:26 PM, Caleb C. wrote:

=> “/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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs