Regex in Ruby
This is something simple that I should know off the top of my head, but seemed to have forgotten today. So I’m writing it here, to hopefully, help me to remember.
On one of the webapps I’ve written, someone signed up but had an apostrophe in their name. I had already accounted for spaces in names, but not apostrophes. So, I decided that I should fix things for any non-word character.
The method that cleans up the name is this:
def fullname_no_spaces [firstname.gsub(" ","_"), lastname.gsub(" ","_")].join("_") end
This just substitutes any spaces it finds with an underscore. To have it replace any non-word character with an underscore, I just changed it to this:
def fullname_no_spaces [firstname.gsub(/\W/,"_"), lastname.gsub(/\W/,"_")].join("_") end
That fixed my problems. For further reference, here are the regex values I could use:
^ beginning of a line or string $ end of a line or string . any character except newline \w word character[0-9A-Za-z_] \W non-word character \s whitespace character[ \t\n\r\f] \S non-whitespace character \d digit, same as[0-9] \D non-digit \A beginning of a string \Z end of a string, or before newline at the end \z end of a string \b word boundary(outside[]only) \B non-word boundary \b backspace(0x08)(inside[]only) [ ] any single character of set * 0 or more previous regular expression *? 0 or more previous regular expression(non greedy) + 1 or more previous regular expression +? 1 or more previous regular expression(non greedy) {m,n} at least m but most n previous regular expression {m,n}? at least m but most n previous regular expression(non greedy) ? 0 or 1 previous regular expression | alternation ( ) grouping regular expressions (?# ) comment (?: ) grouping without backreferences (?= ) zero-width positive look-ahead assertion (?! ) zero-width negative look-ahead assertion (?ix-ix) turns on (or off) `i' and `x' options within regular expression.
I use a few of these a lot, but I need to remember all of them because they’re really handy. Perhaps, I’ll make a printout and hang it in my office.