Rev 69659 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
% File src/library/base/man/regex.Rd% Part of the R package, https://www.R-project.org% Copyright 1995-2015 R Core Team% Distributed under GPL 2 or later\name{regex}\alias{regex}\alias{regexp}\alias{regular expression}\concept{regular expression}\title{Regular Expressions as used in R}\description{This help page documents the regular expression patterns supported by\code{\link{grep}} and related functions \code{grepl}, \code{regexpr},\code{gregexpr}, \code{sub} and \code{gsub}, as well as by\code{\link{strsplit}}.}\details{A \sQuote{regular expression} is a pattern that describes a set ofstrings. Two types of regular expressions are used in \R,\emph{extended} regular expressions (the default) and\emph{Perl-like} regular expressions used by \code{perl = TRUE}.There is a also \code{fixed = TRUE} which can be considered to use a\emph{literal} regular expression.Other functions which use regular expressions (often via the use of\code{grep}) include \code{apropos}, \code{browseEnv},\code{help.search}, \code{list.files} and \code{ls}.These will all use \emph{extended} regular expressions.Patterns are described here as they would be printed by \code{cat}:(\emph{do remember that backslashes need to be doubled when entering \Rcharacter strings}, e.g.\sspace{}from the keyboard).Long regular expressions may or may not be accepted: the POSIXstandard only requires up to 256 \emph{bytes}.}\section{Extended Regular Expressions}{This section covers the regular expressions allowed in the defaultmode of \code{grep}, \code{regexpr}, \code{gregexpr}, \code{sub},\code{gsub} and \code{strsplit}. They use an implementation of thePOSIX 1003.2 standard: that allows some scope for interpretation andthe interpretations here are those currently used by \R. Theimplementation supports some extensions to the standard.Regular expressions are constructed analogously to arithmeticexpressions, by using various operators to combine smallerexpressions. The whole expression matches zero or more characters(read \sQuote{character} as \sQuote{byte} if \code{useBytes = TRUE}).The fundamental building blocks are the regular expressions that matcha single character. Most characters, including all letters anddigits, are regular expressions that match themselves. Anymetacharacter with special meaning may be quoted by preceding it witha backslash. The metacharacters in extended regular expressions are\samp{. \\ | ( ) [ \{ ^ $ * + ?}, but note that whether these have aspecial meaning depends on the context.Escaping non-metacharacters with a backslash isimplementation-dependent. The current implementation interprets\samp{\\a} as \samp{BEL}, \samp{\\e} as \samp{ESC}, \samp{\\f} as\samp{FF}, \samp{\\n} as \samp{LF}, \samp{\\r} as \samp{CR} and\samp{\\t} as \samp{TAB}. (Note that these will be interpreted by\R's parser in literal character strings.)A \emph{character class} is a list of characters enclosed between\samp{[} and \samp{]} which matches any single character in that list;unless the first character of the list is the caret \samp{^}, when itmatches any character \emph{not} in the list. For example, theregular expression \samp{[0123456789]} matches any single digit, and\samp{[^abc]} matches anything except the characters \samp{a},\samp{b} or \samp{c}. A range of characters may be specified bygiving the first and last characters, separated by a hyphen. (Becausetheir interpretation is locale- and implementation-dependent,character ranges are best avoided.) The only portable way to specifyall ASCII letters is to list them all as the character class\cr\samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]}.\cr (Thecurrent implementation uses numerical order of the encoding.)Certain named classes of characters are predefined. Theirinterpretation depends on the \emph{locale} (see \link{locales}); theinterpretation below is that of the POSIX locale.\describe{\item{\samp{[:alnum:]}}{Alphanumeric characters: \samp{[:alpha:]}and \samp{[:digit:]}.}\item{\samp{[:alpha:]}}{Alphabetic characters: \samp{[:lower:]} and\samp{[:upper:]}.}\item{\samp{[:blank:]}}{Blank characters: space and tab, andpossibly other locale-dependent characters such as non-breakingspace.}\item{\samp{[:cntrl:]}}{Control characters. In ASCII, these characters have octal codes000 through 037, and 177 (\code{DEL}). In another character set,these are the equivalent characters, if any.}\item{\samp{[:digit:]}}{Digits: \samp{0 1 2 3 4 5 6 7 8 9}.}\item{\samp{[:graph:]}}{Graphical characters: \samp{[:alnum:]} and\samp{[:punct:]}.}\item{\samp{[:lower:]}}{Lower-case letters in the current locale.}\item{\samp{[:print:]}}{Printable characters: \samp{[:alnum:]}, \samp{[:punct:]} and space.}\item{\samp{[:punct:]}}{Punctuation characters:\cr\samp{! " # $ \% & ' ( ) * + , - . / : ; < = > ? @ [ \\ ] ^ _ ` \{ | \} ~}.}%'"` keep Emacs Rd mode happy\item{\samp{[:space:]}}{Space characters: tab, newline, vertical tab, form feed, carriagereturn, space and possibly other locale-dependent characters.}\item{\samp{[:upper:]}}{Upper-case letters in the current locale.}\item{\samp{[:xdigit:]}}{Hexadecimal digits:\cr\samp{0 1 2 3 4 5 6 7 8 9 A B C D E F a b c d e f}.}}For example, \samp{[[:alnum:]]} means \samp{[0-9A-Za-z]}, except thelatter depends upon the locale and the character encoding, whereas theformer is independent of locale and character set. (Note that thebrackets in these class names are part of the symbolic names, and mustbe included in addition to the brackets delimiting the bracket list.)Most metacharacters lose their special meaning inside a characterclass. To include a literal \samp{]}, place it first in the list.Similarly, to include a literal \samp{^}, place it anywhere but first.Finally, to include a literal \samp{-}, place it first or last (or,for \code{perl = TRUE} only, precede it by a backslash). (Only\samp{^ - \\ ]} are special inside character classes.)The period \samp{.} matches any single character. The symbol\samp{\\w} matches a \sQuote{word} character (a synonym for\samp{[[:alnum:]_]}, an extension) and \samp{\\W} is its negation(\samp{[^[:alnum:]_]}). Symbols \samp{\\d}, \samp{\\s}, \samp{\\D}and \samp{\\S} denote the digit and space classes and their negations(these are all extensions).The caret \samp{^} and the dollar sign \samp{$} are metacharactersthat respectively match the empty string at the beginning and end of aline. The symbols \samp{\\<} and \samp{\\>} match the empty string atthe beginning and end of a word. The symbol \samp{\\b} matches theempty string at either edge of a word, and \samp{\\B} matches theempty string provided it is not at an edge of a word. (Theinterpretation of \sQuote{word} depends on the locale andimplementation: these are all extensions.)A regular expression may be followed by one of several repetitionquantifiers:\describe{\item{\samp{?}}{The preceding item is optional and will be matchedat most once.}\item{\samp{*}}{The preceding item will be matched zero or moretimes.}\item{\samp{+}}{The preceding item will be matched one or moretimes.}\item{\samp{{n}}}{The preceding item is matched exactly \code{n}times.}\item{\samp{{n,}}}{The preceding item is matched \code{n} or moretimes.}\item{\samp{{n,m}}}{The preceding item is matched at least \code{n}times, but not more than \code{m} times.}}By default repetition is greedy, so the maximal possible number ofrepeats is used. This can be changed to \sQuote{minimal} by appending\code{?} to the quantifier. (There are further quantifiers that allowapproximate matching: see the TRE documentation.)Regular expressions may be concatenated; the resulting regularexpression matches any string formed by concatenating the substringsthat match the concatenated subexpressions.Two regular expressions may be joined by the infix operator \samp{|};the resulting regular expression matches any string matching eithersubexpression. For example, \samp{abba|cde} matches either thestring \code{abba} or the string \code{cde}. Note that alternationdoes not work inside character classes, where \samp{|} has its literalmeaning.Repetition takes precedence over concatenation, which in turn takesprecedence over alternation. A whole subexpression may be enclosed inparentheses to override these precedence rules.The backreference \samp{\\N}, where \samp{N = 1 ... 9}, matchesthe substring previously matched by the Nth parenthesizedsubexpression of the regular expression. (This is anextension for extended regular expressions: POSIX defines them onlyfor basic ones.)}\section{Perl-like Regular Expressions}{The \code{perl = TRUE} argument to \code{grep}, \code{regexpr},\code{gregexpr}, \code{sub}, \code{gsub} and \code{strsplit} switchesto the PCRE library that implements regular expression patternmatching using the same syntax and semantics as Perl 5.x,with just a few differences.For complete details please consult the man pages for PCRE (and notPCRE2), especially \command{man pcrepattern} and \command{manpcreapi}), on your system or from the sources at\url{http://www.pcre.org}. If PCRE support was compiled from thesources within \R (the default), the PCRE version is 8.37 as describedhere. (The version in use can be found by calling\code{\link{extSoftVersion}}.)Perl regular expressions can be computed byte-by-byte or(UTF-8) character-by-character: the latter is used in all multibytelocales and if any of the inputs are marked as UTF-8 (see\code{\link{Encoding}}).All the regular expressions described for extended regular expressionsare accepted except \samp{\\<} and \samp{\\>}: in Perl all backslashedmetacharacters are alphanumeric and backslashed symbols always areinterpreted as a literal character. \samp{\{} is not special if itwould be the start of an invalid interval specification. There can bemore than 9 backreferences (but the replacement in \code{\link{sub}}can only refer to the first 9).Character ranges are interpreted in the numerical order of thecharacters, either as bytes in a single-byte locale or as Unicode codepoints in UTF-8 mode. So in either case \samp{[A-Za-z]} specifies theset of ASCII letters.In UTF-8 mode the named character classes only match ASCII characters:see \samp{\\p} below for an alternative.The construct \samp{(?...)} is used for Perl extensions in a varietyof ways depending on what immediately follows the \samp{?}.Perl-like matching can work in several modes, set by the options\samp{(?i)} (caseless, equivalent to Perl's \samp{/i}), \samp{(?m)}(multiline, equivalent to Perl's \samp{/m}), \samp{(?s)} (single line,so a dot matches all characters, even new lines: equivalent to Perl's\samp{/s}) and \samp{(?x)} (extended, whitespace data characters areignored unless escaped and comments are allowed: equivalent to Perl's\samp{/x}). These can be concatenated, so for example, \samp{(?im)}sets caseless multiline matching. It is also possible to unset theseoptions by preceding the letter with a hyphen, and to combine settingand unsetting such as \samp{(?im-sx)}. These settings can be appliedwithin patterns, and then apply to the remainder of the pattern.Additional options not in Perl include \samp{(?U)} to set\sQuote{ungreedy} mode (so matching is minimal unless \samp{?} is usedas part of the repetition quantifier, when it is greedy). Initiallynone of these options are set.If you want to remove the special meaning from a sequence ofcharacters, you can do so by putting them between \samp{\\Q} and\samp{\\E}. This is different from Perl in that \samp{$} and \samp{@} arehandled as literals in \samp{\\Q...\\E} sequences in PCRE, whereas inPerl, \samp{$} and \samp{@} cause variable interpolation.The escape sequences \samp{\\d}, \samp{\\s} and \samp{\\w} representany decimal digit, space character and \sQuote{word} character(letter, digit or underscore in the current locale: in UTF-8 mode onlyASCII letters and digits are considered) respectively, and theirupper-case versions represent their negation. Vertical tab was notregarded as a space character in a \code{C} locale before PCRE 8.34(included in \R 3.0.3). Sequences \samp{\\h}, \samp{\\v}, \samp{\\H}and \samp{\\V} match horizontal and vertical space or the negation.(In UTF-8 mode, these do match non-ASCII Unicode code points.)There are additional escape sequences: \samp{\\cx} is\samp{cntrl-x} for any \samp{x}, \samp{\\ddd} is theoctal character (for up to three digits unlessinterpretable as a backreference, as \samp{\\1} to \samp{\\7} alwaysare), and \samp{\\xhh} specifies a character by two hex digits.In a UTF-8 locale, \samp{\\x\{h...\}} specifies a Unicode code pointby one or more hex digits. (Note that some of these will beinterpreted by \R's parser in literal character strings.)Outside a character class, \samp{\\A} matches at the start of asubject (even in multiline mode, unlike \samp{^}), \samp{\\Z} matchesat the end of a subject or before a newline at the end, \samp{\\z}matches only at end of a subject. and \samp{\\G} matches at firstmatching position in a subject (which is subtly different from Perl'send of the previous match). \samp{\\C} matches a singlebyte, including a newline, but its use is warned against. In UTF-8mode, \samp{\\R} matches any Unicode newline character (not just CR),and \samp{\\X} matches any number of Unicode characters that form anextended Unicode sequence.In UTF-8 mode, some Unicode properties may be supported via\samp{\p{xx}} and \samp{\P{xx}} which match characters with andwithout property \samp{xx} respectively. For a list of supportedproperties see the PCRE documentation, but for example \samp{Lu} is\sQuote{upper case letter} and \samp{Sc} is \sQuote{currency symbol}.(This support depends on the PCRE library being compiled with\sQuote{Unicode property support}: an external library might not be.It can be checked \emph{via} \code{\link{pcre_config}}.)The sequence \samp{(?#} marks the start of a comment which continuesup to the next closing parenthesis. Nested parentheses are notpermitted. The characters that make up a comment play no part at all inthe pattern matching.If the extended option is set, an unescaped \samp{#} character outsidea character class introduces a comment that continues up to the nextnewline character in the pattern.The pattern \samp{(?:...)} groups characters just as parentheses dobut does not make a backreference.Patterns \samp{(?=...)} and \samp{(?!...)} are zero-width positive andnegative lookahead \emph{assertions}: they match if an attempt tomatch the \code{\dots} forward from the current position would succeed(or not), but use up no characters in the string being processed.Patterns \samp{(?<=...)} and \samp{(?<!...)} are the lookbehindequivalents: they do not allow repetition quantifiers nor \samp{\\C}in \code{\dots}.\code{regexpr} and \code{gregexpr} support \sQuote{named capture}. Ifgroups are named, e.g., \code{"(?<first>[A-Z][a-z]+)"} then thepositions of the matches are also returned by name. (Namedbackreferences are not supported by \code{sub}.)Atomic grouping, possessive qualifiers and conditionaland recursive patterns are not covered here.}\author{This help page is based on the TRE documentation and the POSIXstandard, and the \code{pcrepattern} man page from PCRE 8.36.}\seealso{\code{\link{grep}}, \code{\link{apropos}}, \code{\link{browseEnv}},\code{\link{glob2rx}}, \code{\link{help.search}}, \code{\link{list.files}},\code{\link{ls}} and \code{\link{strsplit}}.The TRE documentation at\url{http://laurikari.net/tre/documentation/regex-syntax/}).The POSIX 1003.2 standard at\url{http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html}The \code{pcrepattern} \command{man} page (found as part of\url{http://www.pcre.org/original/pcre.txt}), and details of Perl's ownimplementation at \url{http://perldoc.perl.org/perlre.html}.}\keyword{character}