strip doesn't take a character set?

X

Xeno Campanoli

I wanna do something like newstr = str.strip(/\D/)

I know I could do newstr = str.sub(/^\D*/,'').sub(/\D*$/,''), but is there any
better way?

xc
 
R

Robert Klemme

I wanna do something like newstr = str.strip(/\D/)

I know I could do newstr = str.sub(/^\D*/,'').sub(/\D*$/,''), but is there any
better way?

Maybe

newstr = str.sub /\A\D*(.*?)\D*\z/, '\\1'
newstr = str[/\A\D*(.*?)\D*\z/, 1]

Kind regards

robert
 
T

trans

I wanna do something like newstr =3D str.strip(/\D/)

I know I could do newstr =3D str.sub(/^\D*/,'').sub(/\D*$/,''), but is th= ere any
better way?

Maybe

str.sub(/^\D*(.*)\D*$/, '\1')

T.
 
J

Joel VanderWerf

I wanna do something like newstr = str.strip(/\D/)
I know I could do newstr = str.sub(/^\D*/,'').sub(/\D*$/,''), but is there
any
better way?

Use #slice / #[]:

irb(main):006:0> s = "aaa111bbb222ccc"
=> "aaa111bbb222ccc"
irb(main):007:0> s[/\A\D*(.*)\D*\z/, 1]
=> "111bbb222ccc"
 
J

Joel VanderWerf

I wanna do something like newstr = str.strip(/\D/)
I know I could do newstr = str.sub(/^\D*/,'').sub(/\D*$/,''), but is
there
any
better way?

Use #slice / #[]:

irb(main):006:0> s = "aaa111bbb222ccc"
=> "aaa111bbb222ccc"
irb(main):007:0> s[/\A\D*(.*)\D*\z/, 1]
=> "111bbb222ccc"

Oops, gotta be non-greedy:

irb(main):001:0> s = "aaa111bbb222ccc"
=> "aaa111bbb222ccc"
irb(main):002:0> s[/\A\D*(.*?)\D*\z/, 1]
=> "111bbb222"
 
D

Daniel DeLorme

Robert said:
I wanna do something like newstr = str.strip(/\D/)

I know I could do newstr = str.sub(/^\D*/,'').sub(/\D*$/,''), but is
there any better way?

Maybe

newstr = str.sub /\A\D*(.*?)\D*\z/, '\\1'
newstr = str[/\A\D*(.*?)\D*\z/, 1]

And a final tweak to account for \n:
newstr = str.sub /\A\D*(.*?)\D*\z/m, '\\1'
newstr = str[/\A\D*(.*?)\D*\z/m, 1]
 

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,172
Messages
2,570,934
Members
47,477
Latest member
ColumbusMa

Latest Threads

Top