ruby 正则表达式 ruby-doc原文

Regexp

A Regexp holds a regular expression, used to match a pattern against strings. Regexps are created using the /.../ and %r{...} literals, and by the Regexp::new constructor.

Regular expressions (regexps) are patterns which describe the contents of a string. They’re used for testing whether a string contains a given pattern, or extracting the portions that match. They are created with the /pat/ and %r{pat} literals or the Regexp.new constructor.

A regexp is usually delimited with forward slashes (/). For example:

/hay/=~'haystack'#=> 0/y/.match('haystack') #=> #<MatchData "y">

If a string contains the pattern it is said to match. A literal string matches itself.

# 'haystack' does not contain the pattern 'needle', so doesn't match./needle/.match('haystack') #=> nil# 'haystack' does contain the pattern 'hay', so it matches/hay/.match('haystack') #=> #<MatchData "hay">

Specifically, /st/ requires that the string contains the letter s followed by the letter t, so it matches haystack, also.

The following are metacharacters(, ), [, ], {, }, ., ?, +, *. They have a specific meaning when appearing in a pattern. To match them literally they must be backslash-escaped. To match a backslash literally backslash-escape that: <tt>\\</tt>.

/1 \+ 2 = 3\?/.match('Does 1 + 2 = 3?') #=> #<MatchData "1 + 2 = 3?">

Patterns behave like double-quoted strings so can contain the same backslash escapes.

/\s\u{6771 4eac 90fd}/.match("Go to 東京都") #=> #<MatchData " 東京都">

Arbitrary Ruby expressions can be embedded into patterns with the #{...} construct.

A character class is delimited with square brackets ([, ]) and lists characters that may appear at that point in the match. /[ab]/ means a or b, as opposed to /ab/ which means a followed by b.

/W[aeiou]rd/.match("Word") #=> #<MatchData "Word">

Within a character class the hyphen (-) is a metacharacter denoting an inclusive range of characters. [abcd] is equivalent to [a-d]. A range can be followed by another range, so [abcdwxyz] is equivalent to [a-dw-z]. The order in which ranges or individual characters appear inside a character class is irrelevant.

If the first character of a character class is a caret (^) the class is inverted: it matches any character except those named.

/[^a-eg-z]/.match('f') #=> #<MatchData "f">

A character class may contain another character class. By itself this isn’t useful because [a-z[0-9]] describes the same set as [a-z0-9]. However, character classes also support the && operator which performs set intersection on its arguments. The two can be combined as follows:

/[a-w&&[^c-g]z]/ # ([a-w] AND ([^c-g] OR z)) # This is equivalent to: /[abh-w]/

The following metacharacters also behave like character classes:

/./ - Any character except a newline.

/./m - Any character (the m modifier enables multiline mode)

/\w/ - A word character ([a-zA-Z0-9_])

/\W/ - A non-word character ([^a-zA-Z0-9_])

/\d/ - A digit character ([0-9])

/\D/ - A non-digit character ([^0-9])

/\h/ - A hexdigit character ([0-9a-fA-F])

/\H/ - A non-hexdigit character ([^0-9a-fA-F])

/\s/ - A whitespace character: /[ \t\r\n\f]/

/\S/ - A non-whitespace character: /[^ \t\r\n\f]/

POSIX bracket expressions are also similar to character classes. They provide a portable alternative to the above, with the added benefit that they encompass non-ASCII characters. For instance, /\d/ matches only the ASCII decimal digits (0-9); whereas /[[:digit:]]/ matches any character in the Unicode Nd category.

/[[:alnum:]]/ - Alphabetic and numeric character

/[[:alpha:]]/ - Alphabetic character

/[[:blank:]]/ - Space or tab

/[[:cntrl:]]/ - Control character

/[[:digit:]]/ - Digit

/[[:graph:]]/ - Non-blank character (excludes spaces, control characters, and similar)

/[[:lower:]]/ - Lowercase alphabetical character

/[[:print:]]/ - Like [:graph:], but includes the space character

/[[:punct:]]/ - Punctuation character

/[[:space:]]/ - Whitespace character ([:blank:], newline,

carriage return, etc.)

/[[:upper:]]/ - Uppercase alphabetical

/[[:xdigit:]]/ - Digit allowed in a hexadecimal number (i.e., 0-9a-fA-F)

Ruby also supports the following non-POSIX character classes:

/[[:word:]]/ - A character in one of the following Unicode general categories Letter, Mark, Number, Connector_Punctuation

The constructs described so far match a single character. They can be followed by a repetition metacharacter to specify how many times they need to occur. Such metacharacters are called quantifiers.

* - Zero or more times

+ - One or more times

? - Zero or one times (optional)

{n} - Exactly n times

{n,} - n or more times

{,m} - m or less times

{n,m} - At least n and at most m times

# At least one uppercase character ('H'), at least one lowercase# character ('e'), two 'l' characters, then one 'o'"Hello".match(/[[:upper:]]+[[:lower:]]+l{2}o/) #=> #<MatchData "Hello">

Repetition is greedy by default: as many occurrences as possible are matched while still allowing the overall match to succeed. By contrast, lazy matching makes the minimal amount of matches necessary for overall success. A greedy metacharacter can be made lazy by following it with ?.

# Both patterns below match the string. The first uses a greedy# quantifier so '.+' matches '<a><b>'; the second uses a lazy# quantifier so '.+?' matches '<a>'./<.+>/.match("<a><b>") #=> #<MatchData "<a><b>">/<.+?>/.match("<a><b>") #=> #<MatchData "<a>">

A quantifier followed by + matches possessively: once it has matched it does not backtrack. They behave like greedy quantifiers, but having matched they refuse to “give up” their match even if this jeopardises the overall match.

Parentheses can be used for capturing. The text enclosed by the n<sup>th</sup> group of parentheses can be subsequently referred to with n. Within a pattern use the backreference</tt>n; outside of the pattern use <tt>MatchData[n].

# 'at' is captured by the first group of parentheses, then referred to# later with \1/[csh](..) [csh]\1 in/.match("The cat sat in the hat") #=> #<MatchData "cat sat in" 1:"at"># Regexp#match returns a MatchData object which makes the captured# text available with its #[] method./[csh](..) [csh]\1 in/.match("The cat sat in the hat")[1] #=> 'at'

Capture groups can be referred to by name when defined with the (?<name>) or (?'name') constructs.

The (?:…) construct provides grouping without capturing. That is, it combines the terms it contains into an atomic whole without creating a backreference. This benefits performance at the slight expense of readabilty.

# The group of parentheses captures 'n' and the second 'ti'. The# second group is referred to later with the backreference \2/I(n)ves(ti)ga\2ons/.match("Investigations") #=> #<MatchData "Investigations" 1:"n" 2:"ti"># The first group of parentheses is now made non-capturing with '?:',# so it still matches 'n', but doesn't create the backreference. Thus,# the backreference \1 now refers to 'ti'./I(?:n)ves(ti)ga\1ons/.match("Investigations") #=> #<MatchData "Investigations" 1:"ti">

Grouping can be made atomic with (?>pat). This causes the subexpression pat to be matched independently of the rest of the expression such that what it matches becomes fixed for the remainder of the match, unless the entire subexpression must be abandoned and subsequently revisited. In this way pat is treated as a non-divisible whole. Atomic grouping is typically used to optimise patterns so as to prevent the regular expression engine from backtracking needlesly.

# The <tt>"</tt> in the pattern below matches the first character of# the string, then <tt>.*</tt> matches <i>Quote"</i>. This causes the# overall match to fail, so the text matched by <tt>.*</tt> is# backtracked by one position, which leaves the final character of the# string available to match <tt>"</tt>/".*"/.match('"Quote"') #=> #<MatchData "\"Quote\""># If <tt>.*</tt> is grouped atomically, it refuses to backtrack# <i>Quote"</i>, even though this means that the overall match fails/"(?>.*)"/.match('"Quote"') #=> nil

The \g<name> syntax matches the previous subexpression named name, which can be a group name or number, again. This differs from backreferences in that it re-executes the group rather than simply trying to re-match the same text.

# Matches a <i>(</i> character and assigns it to the <tt>paren</tt># group, tries to call that the <tt>paren</tt> sub-expression again# but fails, then matches a literal <i>)</i>./\A(?<paren>\(\g<paren>*\))*\z/=~'()'/\A(?<paren>\(\g<paren>*\))*\z/=~'(())'#=> 0# ^1# ^2# ^3# ^4# ^5# ^6# ^7# ^8# ^9# ^10

Matches at the beginning of the string, i.e. before the first character.

Enters a named capture group called paren

Matches a literal (, the first character in the string

Calls the paren group again, i.e. recurses back to the second step

Re-enters the paren group

Matches a literal (, the second character in the string

Try to call paren a third time, but fail because doing so would prevent an overall successful match

Match a literal ), the third character in the string. Marks the end of the second recursive call

(?=pat) - Positive lookahead assertion: ensures that the following characters match pat, but doesn't include those characters in the matched text

(?!pat) - Negative lookahead assertion: ensures that the following characters do not match pat, but doesn't include those characters in the matched text

(?<=pat) - Positive lookbehind assertion: ensures that the preceding characters match pat, but doesn't include those characters in the matched text

(?<!pat) - Negative lookbehind assertion: ensures that the preceding characters do not match pat, but doesn't include those characters in the matched text

# If a pattern isn't anchored it can begin at any point in the string/real/.match("surrealist") #=> #<MatchData "real"># Anchoring the pattern to the beginning of the string forces the# match to start there. 'real' doesn't occur at the beginning of the# string, so now the match fails/\Areal/.match("surrealist") #=> nil# The match below fails because although 'Demand' contains 'and', thepatterndoesnotoccuratawordboundary. /\band/.match("Demand") # Whereas in the following example 'and' has been anchored to a# non-word boundary so instead of matching the first 'and' it matches# from the fourth letter of 'demand' instead/\Band.+/.match("Supply and demand curve") #=> #<MatchData "and curve"># The pattern below uses positive lookahead and positive lookbehind to# match text appearing in <b></b> tags without including the tags in the# match/(?<=<b>)\w+(?=<\/b>)/.match("Fortune favours the <b>bold</b>") #=> #<MatchData "bold">

As mentioned above, the x option enables free-spacing mode. Literal white space inside the pattern is ignored, and the octothorpe (#) character introduces a comment until the end of the line. This allows the components of the pattern to be organised in a potentially more readable fashion.

# A contrived pattern to match a number with optional decimal placesfloat_pat = /\A [[:digit:]]+ # 1 or more digits before the decimal point (\. # Decimal point [[:digit:]]+ # 1 or more digits after the decimal point )? # The decimal point and following digits are optional \Z/float_pat.match('3.14') #=> #<MatchData "3.14" 1:".14">

Note: To match whitespace in an x pattern use an escape such as \s or \p{Space}.

Comments can be included in a non-x pattern with the (?#comment) construct, where comment is arbitrary text ignored by the regexp engine.

A regexp can be matched against a string when they either share an encoding, or the regexp’s encoding is US-ASCII and the string’s encoding is ASCII-compatible.

If a match between incompatible encodings is attempted an Encoding::CompatibilityError exception is raised.

The Regexp#fixed_encoding? predicate indicates whether the regexp has a fixed encoding, that is one incompatible with ASCII. A regexp’s encoding can be explicitly fixed by supplying Regexp::FIXEDENCODING as the second argument of Regexp.new:

Certain pathological combinations of constructs can lead to abysmally bad performance.

Consider a string of 25 as, a d, 4 as, and a c.

s = 'a'*25+'d''a'*4+'c'#=> "aaaaaaaaaaaaaaaaaaaaaaaaadadadadac"

The following patterns match instantly as you would expect:

/(b|a)/=~s#=> 0/(b|a+)/=~s#=> 0/(b|a+)*\/ =~ s #=> 0

However, the following pattern takes appreciably longer:

/(b|a+)*c/=~s#=> 32

This happens because an atom in the regexp is quantified by both an immediate + and an enclosing * with nothing to differentiate which is in control of any particular character. The nondeterminism that results produces super-linear performance. (Consult Mastering Regular Expressions (3rd ed.), pp 222, by Jeffery Friedl, for an in-depth analysis). This particular case can be fixed by use of atomic grouping, which prevents the unnecessary backtracking:

The 29 optional as match the string, but this prevents the 29 mandatory as that follow from matching. Ruby must then backtrack repeatedly so as to satisfy as many of the optional matches as it can while still matching the mandatory 29. It is plain to us that none of the optional matches can succeed, but this fact unfortunately eludes Ruby.

One approach for improving performance is to anchor the match to the beginning of the string, thus significantly reducing the amount of backtracking needed.

Constants

Public Class Methods

compile(*args)

Synonym for Regexp.new

escape(str) → string

Escapes any characters that would have special meaning in a regular expression. Returns a new escaped string, or self if no characters are escaped. For any string, Regexp.new(Regexp.escape(str))=~str will be true.

Regexp.escape('\*?{}.') #=> \\\*\?\{\}\.

last_match → matchdata

last_match(n) → str

The first form returns the MatchData object generated by the last successful pattern match. Equivalent to reading the global variable $~. The second form returns the nth field in this MatchData object. n can be a string or symbol to reference a named capture.

Note that the last_match is local to the thread and method scope of the method that did the pattern match.

Constructs a new regular expression from pattern, which can be either a String or a Regexp (in which case that regexp’s options are propagated, and new options may not be specified (a change as of Ruby 1.8). If options is a Fixnum, it should be one or more of the constants Regexp::EXTENDED, Regexp::IGNORECASE, and Regexp::MULTILINE, or-ed together. Otherwise, if options is not nil, the regexp will be case insensitive. When the lang parameter is `n’ or `N’ sets the regexp no encoding.

Escapes any characters that would have special meaning in a regular expression. Returns a new escaped string, or self if no characters are escaped. For any string, Regexp.new(Regexp.escape(str))=~str will be true.

Regexp.escape('\*?{}.') #=> \\\*\?\{\}\.

try_convert(obj) → re or nil

Try to convert obj into a Regexp, using to_regexp method. Returns converted regexp or nil if obj cannot be converted for any reason.

Return a Regexp object that is the union of the given patterns, i.e., will match any of its parts. The patterns can be Regexp objects, in which case their options will be preserved, or Strings. If no patterns are given, returns /(?!)/. The behavior is unspecified if any given pattern contains capture.

If =~ is used with a regexp literal with named captures, captured strings (or nil) is assigned to local variables named by the capture names.

/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/=~" x = y "plhs#=> "x"prhs#=> "y"

If it is not matched, nil is assigned for the variables.

/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/=~" x = "plhs#=> nilprhs#=> nil

This assignment is implemented in the Ruby parser. The parser detects ‘regexp-literal =~ expression’ for the assignment. The regexp must be a literal without interpolation and placed at left hand side.

Produce a hash based on the text and options of this regular expression.

inspect → string

Produce a nicely formatted string-version of rxp. Perhaps surprisingly, #inspect actually produces the more natural version of the string than #to_s.

/ab+c/x.inspect#=> "/ab+c/ix"

match(str) → matchdata or nil

match(str,pos) → matchdata or nil

Returns a MatchData object describing the match, or nil if there was no match. This is equivalent to retrieving the value of the special variable $~ following a normal match. If the second parameter is present, it specifies the position in the string to begin the search.

Returns the set of bits corresponding to the options used when creating this Regexp (see Regexp::new for details. Note that additional bits may be set in the returned options: these are used internally by the regular expression code. These extra bits are ignored if the options are passed to Regexp::new.

Returns a string containing the regular expression and its options (using the (?opts:source) notation. This string can be fed back in to Regexp::new to a regular expression with the same semantics as the original. (However, Regexp#== may not return true when comparing the two, as the source of the regular expression itself may differ, as the example shows). Regexp#inspect produces a generally more readable version of rxp.