Gsub patern


#1

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


#2

On Mon, Dec 22, 2008 at 10:09 AM, elioncho removed_email_address@domain.invalid 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


#3

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
removed_email_address@domain.invalid


#4

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.” removed_email_address@domain.invalid


#5

On Dec 22, 11:42 am, NAYAK removed_email_address@domain.invalid 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
removed_email_address@domain.invalid
http://www.marnen.org


#6

On Mon, Dec 22, 2008 at 10:45 AM, elioncho removed_email_address@domain.invalid 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


#7

Hi,

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

Regards,
NAYAK