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.
8e44b211865cd5915f2f883fd960b56d?d=identicon&s=25 Xeno Campanoli (Guest)
on 2009-06-08 23: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
45196398e9685000d195ec626d477f0e?d=identicon&s=25 Thomas Sawyer (7rans)
on 2009-06-09 00:08
(Received via mailing list)
On Jun 8, 5:57 pm, Xeno Campanoli <xeno.campan...@gmail.com> 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.
47b1910084592eb77a032bc7d8d1a84e?d=identicon&s=25 Joel VanderWerf (Guest)
on 2009-06-09 00: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"
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2009-06-09 00:10
(Received via mailing list)
On 08.06.2009 23:57, Xeno Campanoli 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
47b1910084592eb77a032bc7d8d1a84e?d=identicon&s=25 Joel VanderWerf (Guest)
on 2009-06-09 00: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"
E0526a6bf302e77598ef142d91bdd31c?d=identicon&s=25 Daniel DeLorme (Guest)
on 2009-06-09 02:12
(Received via mailing list)
Robert Klemme wrote:
> On 08.06.2009 23:57, Xeno Campanoli 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.