Ruby/String/match

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

Перейти к: навигация, поиск

Содержание

if you surround a section with (), the data matched is made available separately from the rest.

x = "This is a test".match(/(\w+) (\w+)/)
puts x[0]
puts x[1]
puts x[2]



match doesn"t require a regular expression as an argument, it converts any string supplied into a regular expression

puts "String has vowels" if "This is a test".match("[aeiou]")



Pattern matching with regular expressions

s = "hello"
s =~ /[aeiou]{2}/    # => nil: no double vowels in "hello"
s.match(/[aeiou]/) {|m| m.to_s} # => "e": return first vowel



The !~ operator returns true if it does not match the string, false otherwise:

color = "color colour"
color !~ /colou?r/ # => false



The String class has the =~ method and the !~ operator.

If =~ finds a match, it returns the offset position where the match starts in the string:
color = "color colour"
color =~ /colou?r/ # => 13



use a method called match, provided by the String class

puts "String has vowels" if "This is a test".match(/[aeiou]/)