Ruby/Development/Regexps Repetition
Материал из Wiki.crossplatform.ru
A pattern that matches a string containing the text Perl or the text Python
/Perl|Python/
have Repetition match the minimum by adding a question mark suffix.
def show_regexp(a, re) if a =~ re "#{$`}<<#{$&}>>#{$"}" else "no match" end end a = "this is a test" show_regexp(a, /\w+/) show_regexp(a, /\s.*\s/) show_regexp(a, /\s.*?\s/) show_regexp(a, /[aeiou]{2,99}/) show_regexp(a, /mo?o/)
==Match a time such as /td>
/\d\d:\d\d:\d\d/
match one of a group of characters within apattern
\s matches a white space character(space,tab, newline, and so on); \d matches any digit \w matches any character that may appearin atypical word. . matches any character.
Repetition
r* matches zero or more occurrences of r. r+ matches one or more occurrences of r. r? matches zero or one occurrence of r. r{m,n} matchesatleast "m"and at most "n"occurrencesof r. r{m,} matchesatleast "m"occurrencesof r. r{m} matches exactly "m" occurrences of r. /ab+/ matches an a followed by one or more b"s, not a sequence of ab"s. /a*/ will match any string; every stringhas zero or more a"s.
Replace every occurrence of Perl and Python with Ruby
line = "this is a Perl. And this a Python" puts line line.gsub(/Perl|Python/, "Ruby") puts line
The match operator =~ can be used to match a string against a regular expression.
# If the pattern is found, =~ returns its starting position, or nil. line = "this is a Perl" if line =~ /Perl|Python/ puts "Scripting language mentioned: #{line}" end
The part of a string matched by a regular expression can be replaced
line = "this is a Perl. And this a Python" puts line line.sub(/Perl/, "Ruby") # replace first "Perl" with "Ruby" puts line line.gsub(/Python/, "Ruby") # replace every "Python" with "Ruby" puts line
use back references to match delimiters.
def show_regexp(a, re) if a =~ re "#{$`}<<#{$&}>>#{$"}" else "no match" end end show_regexp("He said "Hello"", /([""]).*?\1/) # He said <<"Hello">> show_regexp("He said "Hello"", /([""]).*?\1/) # He said <<"Hello">>
Use parentheses within patterns,just as you can in arithmetic expressions
# A pattern that matches a string containing the text Perl or the text Python /P(erl|ython)/
use part of the current match later in that match allows you to look for various forms of repetition.
def show_regexp(a, re) if a =~ re "#{$`}<<#{$&}>>#{$"}" else "no match" end end # match duplicated letter show_regexp("He said "Hello"", /(\w)\1/) # He said "He<<ll>>o" # match duplicated substrings show_regexp("Mississippi", /(\w+)\1/) # M<<ississ>>ippi
You can also specify repetition within patterns.
/ab+c/ matches a string containing an a followed by one or more b"s, followed by a c. /ab*c/ matches one a, zero or more b"s, and one c.