2008年3月5日 星期三

regular expression and ruby

/^../ :
/ / to start and end regular expression
^ means beginning of line
. means any character

$ means the end of the line

\A means start of the string
\Z means the end of the string
\w means any character, digit or underscore
\W means anything that does not match \w
\d means any digit
\D means anything that does not match \d
\s whitespace( space, tab, newline)
\S Non-whitespace
+ means match 1 or more of that type of character, match as many as possible
* means match 0 or more of that type of character, match as many as possible
*? means match 0 or more of that type of character, match as few as possible
+ means match 1 or more of that type of character, match as few as possible
? means match 1 or 0 of that type of character
{x} means match x occurrences of that type of character
{x, y} means match as least x times and as most y times
\d+ means match as many digits in a row as possible
\ means escape

ex: "this is a test".scan(/\w\w) { |x| puts x }
scan trough string, find something that match \w\w

ex: "hello".scan(/[aeiou]/
match any of a,e,i,o,u
ex: "hello".scan(/[a-m]/
match any of a to m

matching:
use =~
ex: "this is a test" =~ /[0-9]/
if match, return true, else, return false

use match
ex: "hello".match("[0-9]")

沒有留言: