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

Discussion in 'Ruby' started by deja@homerlex.mailshell.com, May 31, 2006.

  1. Guest

    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!
     
    , May 31, 2006
    #1
    1. Advertising

  2. 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
     
    Robert Klemme, May 31, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Don Hiatt
    Replies:
    3
    Views:
    1,645
    Terry Reedy
    Jul 24, 2003
  2. Replies:
    0
    Views:
    487
  3. Replies:
    5
    Views:
    962
    X-Centric
    Jun 30, 2005
  4. Hongyu
    Replies:
    9
    Views:
    951
    James Kanze
    Aug 8, 2008
  5. John Smith
    Replies:
    8
    Views:
    187
    David K. Wall
    Sep 26, 2003
Loading...

Share This Page