Strip doesn't take a character set?


#1

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


#2

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.


#3

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”


#4

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


#5

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]


#6

=> “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”