Created
July 13, 2012 00:40
-
-
Save pricees/3102059 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
moby = <<EOL | |
Call me Ishmael. Some years ago - never mind how long precisely - having little | |
or no money in my purse, and nothing particular to interest me on shore, I | |
thought I would sail about a little and see the watery part of the world. | |
[Moby Dick - 1st paragraph] | |
EOL | |
# | |
# "." - matches any character | |
# "\s" - matches digits (0-9) | |
# "\S" - matches non-digits | |
# "\s" - matches white-space (space, newline, tabs) | |
# "\S" - matches non-white-space !(space, newline, tabs) | |
# "\S" - matches non-word characters !(a-z, 0-9, _) | |
# "\w" - matches word characters (a-z, 0-9, _) | |
# "\W" - matches non-word characters !(a-z, 0-9, _) | |
# | |
/./ =~ moby # 0 | |
/\s/ =~ moby # 4 | |
/\S/ =~ moby # 0 | |
/\w/ =~ moby # 0 | |
/\W/ =~ moby # 4 | |
/\d/ =~ moby # 242 | |
/\D/ =~ moby # 0 | |
# | |
# [aeiou] - sets, match first occurrence of any | |
# [a-h] - range, match first occurrence of a,b,c...h | |
# | |
/[abc]/ =~ moby # 1 | |
/[F-T]/ =~ moby # 8 | |
# | |
# Negate search | |
# [^pattern] | |
# | |
/[^\D]/ =~ moby # 242 | |
/[^[A-C]]/ =~ moby # 1 | |
# | |
# Either side of the '=~' will work | |
# | |
moby =~ /[Cc]all/ # 0 | |
moby =~ /Call/ # 0 | |
moby =~ /call/ # nil | |
/[Cc]all/ =~ moby # 0 | |
/Call/ =~ moby # 0 | |
/call/ =~ moby # nil | |
# beginnings | |
# ^ matches beginning of string, or line within string | |
# \A matches beginning of string | |
# | |
/^Call/ =~ moby # 0 | |
/^or/ =~ moby # 80 | |
/\ACall/ =~ moby # 0 | |
/\Aor/ =~ moby # nil | |
# endings | |
# $ matches beginning of string, or line within string | |
# \Z matches beginning of string | |
# | |
/little$/ =~ moby # 73 | |
/paragraph\]$/ =~ moby # 246 | |
/little\Z/ =~ moby # nil | |
/paragraph\]\Z/ =~ moby # 246 | |
# regex modifiers | |
# i - case insensitive | |
# m - multiline | |
/ishmael/i =~ moby # 8 | |
/little.*money/m =~ moby #73 # if | |
# | |
# Passively store your match the old way: "$1" | |
# | |
/(never.*)long/ =~ moby | |
$1 # "never mind how" | |
# | |
# Store your answer the cool, hip way | |
# Actively store your match the cool, hip way: | |
# (?<VAR_NAME>pattern) | |
# | |
/(?<never_str>never.*)long/ =~ moby | |
never_str # "never mind how" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment