return string within seperators only

J

Jesse B.

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.
 
C

Caleb Clausen

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
 
R

Robert Klemme

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,158
Messages
2,570,882
Members
47,414
Latest member
djangoframe

Latest Threads

Top