[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Easy way to replace all non-alpha numeric chars in a string?

homerlex

5/31/2006 4:04:00 PM

Is there an easy (clean) method to replace all non-alpha numeric chars
in a string with and underscore?

for example:

I want to transform the following string:

"The book titled 'Ruby is Great' was written on 05/31/2006"

into:

"The_book_titled__Ruby is Great__was written on 05_31_2006"

Thank you in advance!

3 Answers

Tim Hoolihan

5/31/2006 4:11:00 PM

0

def clean(unclean)
return unclean.gsub(/[^A-Z,a-z,0-9]+?/,"_")
end

str = "this is a -test@ stuff"
puts "#{clean(str)}"



deja@homerlex.mailshell.com wrote:
> Is there an easy (clean) method to replace all non-alpha numeric chars
> in a string with and underscore?
>
> for example:
>
> I want to transform the following string:
>
> "The book titled 'Ruby is Great' was written on 05/31/2006"
>
> into:
>
> "The_book_titled__Ruby is Great__was written on 05_31_2006"
>
> Thank you in advance!
>

Tim Hoolihan

5/31/2006 4:14:00 PM

0

sorry that regular expression should have been

return unclean.gsub(/[^A-Z,a-z,0-9, ]+?/,"_")

Tim Hoolihan wrote:
> def clean(unclean)
> return unclean.gsub(/[^A-Z,a-z,0-9]+?/,"_")
> end
>
> str = "this is a -test@ stuff"
> puts "#{clean(str)}"
>
>
>
> deja@homerlex.mailshell.com wrote:
>> Is there an easy (clean) method to replace all non-alpha numeric chars
>> in a string with and underscore?
>>
>> for example:
>>
>> I want to transform the following string:
>>
>> "The book titled 'Ruby is Great' was written on 05/31/2006"
>>
>> into:
>>
>> "The_book_titled__Ruby is Great__was written on 05_31_2006"
>>
>> Thank you in advance!
>>

Robert Klemme

5/31/2006 4:19:00 PM

0

Tim Hoolihan wrote:
> sorry that regular expression should have been
>
> return unclean.gsub(/[^A-Z,a-z,0-9, ]+?/,"_")

No. Commas are no meta characters in character classes:

>> ",".gsub(/[^A-Z,a-z,0-9, ]+?/,"_")
=> ","

You rather want

>> ",".gsub(/[^A-Za-z0-9]+?/,"_")
=> "_"

Alternatively this may work as well

>> ",".gsub(/\W/,"_")
=> "_"

Cheers

robert