Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I strip non alphanumeric characters from a string and keep spaces?

I want to create a regex that removes all non-alphanumber characters but keeps spaces. This is to clean search input before it hits the db. Here's what I have so far:

@search_query = @search_query.gsub(/[^0-9a-z]/i, '') 

Problem here is it removes all the spaces. Solutions on how to retain spaces?

like image 777
TheExit Avatar asked May 23 '11 23:05

TheExit


People also ask

How do you remove a non-alphanumeric character from a string?

Using Regular Expression We can use the regular expression [^a-zA-Z0-9] to identify non-alphanumeric characters in a string. Replace the regular expression [^a-zA-Z0-9] with [^a-zA-Z0-9 _] to allow spaces and underscore character.

How do you get rid of non-alphanumeric?

Non-alphanumeric characters can be remove by using preg_replace() function. This function perform regular expression search and replace. The function preg_replace() searches for string specified by pattern and replaces pattern with replacement if found.

How do you strip a string of non-alphanumeric characters in Python?

1. Using regular expressions. A simple solution is to use regular expressions for removing non-alphanumeric characters from a string. The idea is to use the special character \W , which matches any character which is not a word character.


1 Answers

Add spaces to the negated character group:

@search_query = @search_query.gsub(/[^0-9a-z ]/i, '') 
like image 111
jwueller Avatar answered Oct 26 '22 20:10

jwueller