Gsub patern

Hello,

I am trying to apply a gsub! to a string. I want to know how to make
the pattern evaluate that everything that IS NOT numbers, letters or
commas should be replaced with “”(nil). Any ideas in how to do this
pattern?

Thanks a lot,

Elías

On Mon, Dec 22, 2008 at 10:09 AM, elioncho [email protected] wrote:

Hello,

I am trying to apply a gsub! to a string. I want to know how to make
the pattern evaluate that everything that IS NOT numbers, letters or
commas should be replaced with “”(nil). Any ideas in how to do this
pattern?

irb(main):009:0> “123***,ABC,$$%abc,----+X±—”.gsub(/[^\w,]/, ‘’)
=> “123,ABC,abc,X”

Build a character class with []
Then choose \w and , as characters in the class that you want
(although note that \w includes all alphanumerics and _)
Then negate them both with ^ at the start of the character class

Much more information about Regexp in Ruby can be found here:

http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_stdtypes.html#S4

-Michael


Michael C. Libby
www.mikelibby.com

On Dec 22, 2008, at 11:09 AM, elioncho wrote:

Hello,

I am trying to apply a gsub! to a string. I want to know how to make
the pattern evaluate that everything that IS NOT numbers, letters or
commas should be replaced with “”(nil). Any ideas in how to do this
pattern?

/[^[:alnum:],]/

[^ ] - is a negated character class
[:alnum:] - is the POSIX character class for alphanumerics
, - is a comma :wink:

Thanks a lot,

Elías

Since you have an accented character in you name, I’m assuming that
the [:alnum:] class is better than just a-zA-Z0-9 since it should
encompass the accented characters, too.

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

Thanks a lot Michael, it worked perfectly.

Thanks for the link too, it cleared some things up.

Elías

On Dec 22, 11:23 am, “Michael L.” [email protected]

On Dec 22, 11:42 am, NAYAK [email protected] wrote:

Hi,

You can use gsub(/[^0-9a-zA-Z,]/, ‘’) to replace only non numbers, alphabets
and ,

That’s not reliable if you’re outside an English environment. :alnum:
is a better solution.

Regards,
NAYAK

Best,

Marnen Laibow-Koser
[email protected]
http://www.marnen.org

On Mon, Dec 22, 2008 at 10:45 AM, elioncho [email protected] wrote:

Thanks a lot Michael, it worked perfectly.

Thanks for the link too, it cleared some things up.

Elías

I should mention this neat web site, too:

http://www.rubular.com/

You can try out Ruby regular expressions right in your browser and see
what they match.


Michael C. Libby
www.mikelibby.com

Hi,

You can use gsub(/[^0-9a-zA-Z,]/, ‘’) to replace only non numbers,
alphabets
and ,

Regards,
NAYAK

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs