Forum: Ruby strip doesn't take a character set?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Xeno C. (Guest)
on 2009-06-09 01:58
(Received via mailing list)
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
Thomas S. (Guest)
on 2009-06-09 02:08
(Received via mailing list)
On Jun 8, 5:57 pm, Xeno C. <removed_email_address@domain.invalid> wrote:
> 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

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

T.
Joel VanderWerf (Guest)
on 2009-06-09 02:09
(Received via mailing list)
> 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"
Robert K. (Guest)
on 2009-06-09 02:10
(Received via mailing list)
On 08.06.2009 23:57, Xeno C. wrote:
> 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
Joel VanderWerf (Guest)
on 2009-06-09 02:16
(Received via mailing list)
> => "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"
Daniel DeLorme (Guest)
on 2009-06-09 04:12
(Received via mailing list)
Robert K. wrote:
> On 08.06.2009 23:57, Xeno C. wrote:
>> 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]
This topic is locked and can not be replied to.