Ruby/String/sub with regular expressions

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
м (1 версия)
 

Текущая версия на 17:56, 13 сентября 2010

Содержание

Basic Special Characters and Symbols Within Regular Expressions

Character      Meaning 
^              Anchor for the beginning of a line
$              Anchor for the end of a line
\A             Anchor for the start of a string
\Z             Anchor for the end of a string
.              Any character
\w             Any letter, digit, or underscore
\W             Anything that \w doesn"t match
\d             Any digit
\D             Anything that \D doesn"t match (non-digits)
\s             Whitespace (spaces, tabs, newlines, and so on)
\S             Non-whitespace (any visible character)



Index string by regular expression

s = "My kingdom for a string!"
s[/.ing/]                           # => "king"
s[/str.*/]                          # => "string!"



Regular Expression Character and Sub-Expression Modifiers

Modifier      Description 
*             Match zero or more occurrences of the preceding character, and match as many as possible.
+             Match one or more occurrences of the preceding character, and match as many as possible.
*?            Match zero or more occurrences of the preceding character, and match as few as possible.
+?            Match one or more occurrences of the preceding character, and match as few as possible.
?             Match either one or none of the preceding character.
{x}           Match x occurrences of the preceding character.
{x,y}         Match at least x occurrences and at most y occurrences.



scan is the iterator method you require:

"xyz".scan(/./) { |letter| puts letter }



scan(/../): . means Any character

"This is a test".scan(/../) { |x| puts x }



scan (/\w\w/): \w means Any letter, digit, or underscore

"This is a test".scan(/\w\w/) { |x| puts x }



To change the last two letters

x = "This is a test"
puts x.sub(/..$/, "Hello")



To replace the first two characters of a string with "Hello":

x = "This is a test"
puts x.sub(/^../, "Hello")