Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple regex -- replace underscore with a space

Hey, I'm writing my first Rails app, and I'm trying to replace the underscores form an incoming id name with spaces, like this:

before: test_string

after: test string

How can I do this? Sorry if this is a bit of a dumb question, I'm not very familiar with regular expressions...

like image 368
mportiz08 Avatar asked Aug 28 '09 23:08

mportiz08


People also ask

How do you indicate a space in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

What is the regex for underscore?

The _ (underscore) character in the regular expression means that the zone name must have an underscore immediately following the alphanumeric string matched by the preceding brackets. The . (period) matches any character (a wildcard).

Do you need to escape underscore in regex?

Python Regex Escape Underscore Therefore, you don't need to escape the underscore character—just use it in your regular expression unescaped.


2 Answers

str.gsub!(/_/, ' ') 

gsub stands for 'global substitution', and the exclamation means it'll change the string itself rather than just return the substituted string.

You can also do it without regexes using String#tr!:

str.tr!('_', ' ') 
like image 115
Paige Ruten Avatar answered Sep 27 '22 18:09

Paige Ruten


On rails you can use the simplier .humanize and ruby's .downcase method but be careful as it also strips any final '_id' string (in most cases this is just what you need, even the capitalized first letter)

'text_string_id'.humanize.downcase  => "text string"  
like image 39
Andión Avatar answered Sep 27 '22 18:09

Andión