Skip to content

Instantly share code, notes, and snippets.

@charliegerard
Last active August 29, 2015 13:59
Show Gist options
  • Save charliegerard/10691498 to your computer and use it in GitHub Desktop.
Save charliegerard/10691498 to your computer and use it in GitHub Desktop.

#Regular Expressions

Check ruby-doc.org: http://www.ruby-doc.org/core-1.9.3/Regexp.html

Learning Perl book to learn regular expressions

RegExp can be used in a lot of different languages

Needle is the thing we're looking for

Example:

 /hay/ =~ 'haystack' looks for the string "hay" in the expression "haystack". It will return 0 meaning it found it and it's a position 0.
     


'haystack'[3,3] gives you the first 3 letters at index 3.

If it returns nil, it means it can't find the needle in the expression.

Regular expressions can be used in if statements:

if('haystack' =~ /hay/)
  puts match
end

/bet.y/

If we have '.' in regexp, it checks if it matches any character.

/bet.y/ =~ 'betty'
=>0

Quantifiers:

. any character
* 0 or more  => /bet*y/ =~ 'bettttttty' => 0 
+ 1 or more  => /bet+y/ =~ 'bety' => 0 but 'bey' won't match.
? 0 or 1     => /bet?y/ =~ 'bety' => 0 but 'betttttty' won't match.

We can't combine these quantifiers together:

  /be.?y/ =~ 'bey' => 0
  /be.*y/ => 'bettttttttttaawdsfsrgy' => 0
  /(fred)+/ =~ 'fredfredfred' => you can check if a string is present several times in an expression  
  /fred|barney|wilma/ =~ 'fred' checks if fred OR barney OR wilma matches.
  /bet[st]y/ =~ 'betty' checks if either there is a s or t
  /[Bb]etty/ =~ 'Betty' helps to find if betty has a capitalised or lowercase 'b'.
  /[Bb]etty [0-9]/ =~ 'betty 5' 
  /[^Bb]etty/ =~ 'betty' matches any character that is not a 'b'. so '!etty' will natch.

Regular expression cheatsheet: http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

/vote,[a-z]+,[A-Za-z]+/ =~ 'vote,kick,nix'
/vote,[a-z]+,[A-Za-z]+/.match 'vote,kick,nix' returns Matchdata object
m = /vote,([a-z]+),([A-Za-z]+)/.match 'vote,kick,nix' returns the same MatchData object but we can actually access the info inside it. m[0] will give back everything but m[1] returns the action and m[2] returns the name.

Test regular expressions in the browser: http://rubular.com/


#Testing

Testing on code school: https://www.codeschool.com/courses/testing-with-rspec

Rails testing for zombies: https://www.codeschool.com/courses/rails-testing-for-zombies

The RSPEC Book: http://pragprog.com/book/achbd/the-rspec-book

Cucumber: http://cukes.info/

Folder feature in 05-rails

Capybara

Devise

RegEx Quest Game: http://teabait.github.io/learn-regex/

SASS: http://sass-lang.com/

http://css3please.com/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment