Reg Ex exclusion

N

Ne Scripter

Hi all,

I thought this would be easy, but I am clearly mixing up my logic. I
have a string like so

string = "joe|blogg|clothing|"

I want to remove the last pipe with a reg ex and I am trying to use the
following code to do so:

string(/\|$/, 1)

This however is not doing anything except delete the entire string, any
suggestion are greatly appreciated.

Many thanks
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

Use sub or sub! "joe|blogg|clothing|".sub(/\|$/,'')

On Wed, Sep 2, 2009 at 11:17 AM, Ne Scripter <
 
D

Dylan

Hi all,

I thought this would be easy, but I am clearly mixing up my logic. I
have a string like so

string = "joe|blogg|clothing|"

I want to remove the last pipe with a reg ex and I am trying to use the
following code to do so:

string(/\|$/, 1)

This however is not doing anything except delete the entire string, any
suggestion are greatly appreciated.

Many thanks

Are you actually getting results from "string(/\|$/,1)"? I get what I
would expect:
irb(main):001:0> st="joe|blogg|clothing|"
=> "joe|blogg|clothing|"
irb(main):004:0> st(/(.*)\|$/)
#<Class:0x3f99248>: undefined method `st' for main:Object

I think you mean [ ]

Try this:

string[/(.*)\|$/,1]

irb(main):010:0> st[/(.*)\|$/,1]
=> "joe|blogg|clothing"

By the way, if you're doing this to split up that string into joe,
blogg and clothing later, you can just skip the Regex and use split:

irb(main):011:0> st.split("|")
=> ["joe", "blogg", "clothing"]


-Dylan
 
T

timr

string = "joe|blogg|clothing|"
=> "joe|blogg|clothing|"
string.chop => "joe|blogg|clothing"
string[/(.*)\|$/,1] => "joe|blogg|clothing"
string.split("|").join("|")
=> "joe|blogg|clothing"

The regex solution submitted before is good, though if all of your
cases are this straight forward, I think string.chop is hard to beat.
-tim
 
N

Ne Scripter

Thanks all for your help. I went for the regular expression in the end
for consistency with other code.

Thanks a lot
 

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

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,121
Latest member
LowellMcGu
Top