Regex
This page summarizes some gritty regex details. It's not intended as a tutorial on any of these regex languages, but rather as a technical summary and list of "gotchas" (places where different implementations of a tool may behave in different or unexpected ways).
Glob patterns
These are used in shell expansion and pattern-matching in case
expressions.
glob*
gl?bbing
[a-z]
and[!-aeiou]
[!-aeiou]
can also be expressed in some shells (including BusyBox ash
) as [^-aeiou]
but the [!...]
format is more portable.
- If the pattern contains an invalid bracket expression or does not match any existing filenames or pathnames, the pattern string will be interpreted literally.
- A leading period can only be matched literally, not by
[!a]
or?
or*
or[%-0]
or[[:punct:]]
. In BusyBox ash, it's not matched by[.a]
; other shell implementations may differ. /
can only be matched literally, and has higher parsing precedence than[...]
, soa[b/c]d
only matches file c]d in directory a[b.- Given the pattern
/foo/bar/x*/bam
, search permission is needed for directories / and foo, search and read permissions are needed for directory bar, and search permission is needed for each x* directory. - If
set -f
/set -o noglob
, glob-expansion is disabled.Todo: What contexts automatically suppress glob-expansion?
Q. How do I construct a shell glob-pattern that matches all files except "." and ".." ? (from Unix FAQ 2.11)
Pattern | matches . ? | matches .. ? | matches .a ? | matches .ab ? | matches ..pdq ? | matches xyz ? |
---|---|---|---|---|---|---|
*
|
no | no | no | no | no | yes |
.*
|
yes | yes | yes | yes | yes | no |
.[!.]*
|
no | no | yes | yes | no | no |
.??*
|
no | no | no | yes | yes | no |
Hence, to match all of the four rightmost columns, but neither of the two leftmost ones, you need to combine three glob patterns: * .[!.]* .??*
If you don't have any length-2 filenames like .a, you can go with the simpler: * .??*
POSIX regex
POSIX defines two classes of regex languages: basic regular expressions (BREs) and extended regular expressions (EREs). The first is historically implemented by utilities like grep
, sed
, and ed
. The second by tools like egrep
(grep -E
), awk
, lex
, and emacs
. EREs are usually also available as an option to sed
; sometimes this is expressed using sed -r
, other times sed -E
. (BusyBox sed
uses the first.)
In practice most implementations of these regex languages go beyond the specification, for example including Gnu extensions like \w
, or including features that were only historically available (and are only specified for) the other regex language: thus most implementations of BREs will also honor \+
and \|
, and many implementations of EREs will also honor backreferences like \1
. Additionally, awk
EREs obeys somewhat different rules than other EREs.
One difference between naive implementations of these is that NFAs are more "eager." Both types of engines will return the leftmost of several possible matches in the source text; but the greater eagerness of a NFA would show up in which of several alternative patterns it used to do the matching. For any regex engine which can handle alternative patterns, printf "NFA, no I mean DFA" | regex_match "/NFA|NFA, no I mean DFA/"
would match the whole source text if the engine were a DFA; but would match only "NFA", using the left pattern, if the engine were a (naive) NFA.
However, this is nowadays complicated by the fact that POSIX specifies the longest possible leftmost stretch of source text be matched: so a POSIX-conformant grep
(which accepted pattern alternation as an extension) would have to match "NFA, no I mean DFA", too, just as egrep
would.
POSIX specifies for both BREs and EREs:
- matches should be longest match leftmost in text
- subpatterns match greedily (with matching the empty string "" better than not matching)
- nulls (\0) are not permitted in text nor in patterns
For the following, I've compared the BusyBox tools (grep
, egrep
, sed
with and without -r
, and awk
) to the Gnu core tools, and to the versions of these tools in a base FreeBSD 9 system. I refer to the Gnu implementation of awk
as "gawk" (as Gnu itself does); and I refer to the FreeBSD implementation of awk
as "nawk" (though properly speaking, this is just one among several implementations of nawk).
BREs
This material is work-in-progress ...
|
EREs
This material is work-in-progress ...
|
Gnu extensions
These were present in all the [e]greps I tested with, and in all the seds and awks except nawk
(and gawk --traditional
). They are only treated specially outside of bracket expressions, even in awks, which do still treat \t
and so on specially there.
\w
and\W
for[[:alnum:]_]
and[^[:alnum:]_]
\s
and\S
for[[:space:]]
and[^[:space:]]
, matches any of: space tab \n \r \v \f- (BusyBox tools and some versions of
gawk
lack.)
- (BusyBox tools and some versions of
\b \B \<
and\>
, zero-width matches at word boundaries (non-word-boundaries for\B
)- (In awks,
\b
instead means "\x08";\y
substitutes for\b
ingawk
, nothing substitutes for\b
in BusyBox awk.) - FreeBSD's
[e]grep -o \b...
and[e]grep -o \<...
are currently buggy; and BusyBox's sed and awk are buggy with\< \b \B
at start of words.
- (In awks,
\` \'
start-of-buffer and end-of-buffer anchors (some regex engines not surveyed here use\A \Z \z
for these instead)- (In awks,
^
and$
already have this behavior, even against source texts containing newlines.) - FreeBSD's
[e]grep
currently wrongly match these against start-of-line and end-of-line, rather than start-of-buffer and end-of-buffer. Also, FreeBSD'sgrep -o '\`...'
is buggy in waysgrep -o '...'\'
isn't. BusyBox sed and awk are also buggy with\`
in ways they aren't with\'
. All these bugs have been reported.
- (In awks,
C escapes
\n \t \r \x09 \f \v \a \c
- These are handled specially by awks (though
nawk
only honors up to\f
), even inside brackets. - They are also handled specially by Gnu's sed. BusyBox's sed honors
\n \t \r
; and FreeBSD's sed honors\n
. The other escapes aren't honored by those seds, and none are honored by any grep I tested.
These escapes may also be handled specially by your shell in $'...'
constructs; as too may be \OOO
(up to 3 octal digits) \uXXXX
(4 hex digits) \e \E \b \'
. Awk engines handle some of these latter forms, too. As noted above, the last two are handled differently by some regex engines.
Notes
- All of these regex engines treat
\d
as literal "d", not as[[:digit:]]
.
- BusyBox sed will match only one occurrence of "" (empty string); others will match several of them if the
/g
modifier is on.
- Grep engines will treat newlines in patterns as equivalent to
\|
; sed and awk engines will reject as error.
- FreeBSD's sed will force the presence of terminal
\n
, even if it wasn't present in the input. So too will some other FreeBSD tools likecut
; others liketr
won't. In Gnu's sed, the commandq
also forces a terminal\n
.
- BusyBox's
grep -oz
suffixes each result with "\0" (nul); other greps suffix with\n
.
- Nongreedy quantifiers
pat?? pat*? pat+? pat{m,n}?
aren't provided in the POSIX specification, nor by any of the POSIX-conforming tools discussed here.
- FreeBSD grep and egrep match the empty string at position 0 in:
printf 'cba' | egrep -o '[ba]*'
. None of the other [e]grep implementations I checked (such as BusyBox's or Gnu's) do this.
Regex in Lua
String escapes
In Lua, regex patterns are always supplied as strings, so will honor all the normal escapes on strings:
\\ \" \' \a for bell, \x07 \b for backspace, \x08 \t for \x09 \n for \x0a \v for \x0b \f for \x0c \r for \x0d
Lua strings also accept \ddd
for decimal digits d. (Note: not octal digits.) Starting with Lua 5.2, \xhh
for hex digits is also accepted.
Strings can be written inside matching single or double quotes. They can also be written inside:
[[constructs like this]] [=[ or [[like]] \this]=]
In these constructs, escape sequences like \t
aren't expanded. It and the embedded [[like]]
are both treated literally. Also, the first character of the string is ignored when it's a newline.
Regex engines
The basic Lua regex engine is more limited than the Posix- or PCRE-style languages, though still quite capable. In fact some things are more easily done with the Lua engine than with the more familiar ones. If the basic Lua engine is nonetheless too limited for your purposes, you should look into the LPEG or Lrexlib libraries. The former is more powerful and widely-used in the Lua community; the latter interfaces to more familiar regex engine libraries and languages.
Regex specials
The following sequences have special meaning to the basic Lua regex engine.
- Character classes
-
. Matches any character
%z In Lua 5.1, the regex engine wouldn't read past an embedded \0 in the pattern string, so this special sequence was provided instead to match \0s in the source text (and permit the pattern string to continue). In Lua 5.2, embedded \0s can now be used directly. With the default compilation settings, %z is still honored, but it's deprecated.
%a and %A Like POSIX [[:alpha:]] and [^[:alpha:]] %l and %L Like POSIX [[:lower:]] and [^[:lower:]] %u and %U Like POSIX [[:upper:]] and [^[:upper:]]
%w and %W Like POSIX [[:alnum:]] and [^[:alnum:]]. (Note that unlike the Gnu regex extension\w
, the patterns%w
in Lua and[[:alnum:]]
in POSIX do not match underscores.) %d and %D Like POSIX [[:digit:]] and [^[:digit:]] %x and %X Like POSIX [[:xdigit:]] and [^[:xdigit:]]
%s and %S Like POSIX [[:space:]] and [^[:space:]]. (%s and POSIX [[:space:]] do also match vertical space (\n \r \f \v, whereas POSIX [[:blank:]] matches only \x20 and tab.) %p and %P Like POSIX [[:punct:]] and [^[:punct:]], excludes space and alnum and cntrl %c and %C Like POSIX [[:cntrl:]] and [^[:cntrl:]] %g and %G Like POSIX [[:graph:]] and [^[:graph:]], all visible characters except space; only so interpreted in Lua 5.2 POSIX[[:print:]]
, all visible characters plus space, isn't directly available. Use[%p%w ]
or[%g ]
. - Bracket expressions
- [class] and [^class] can include sequences of:
- single characters like
a
or\t
- ranges like
a-m
- character class specials like
%a
- single characters like
- Groups and backreferences
-
(pat)
Capture the source text matching pat into a group. Unlike other regex engines, these constructions can not be followed by quantifiers like*
or+
%1
Backreference to a captured group (contrast\1
which is and matches "\x01", and\\1
which matches a literal character "\" then "1")()
Instead of text, capture the current position in the matched source into a group
- Quantifiers
-
?
and*
and+
are the familiar greedy quantifiers-
is a nongreedy variant of*
- single characters
- regex specials like
.
and%a
[class]
expressions
(pat)
- Anchors ^ $
- As in POSIX BREs, these are treated as literal characters when not in anchoring positions (as in the pattern
ab^cd
) - Literal characters
- %c This is a literal c, for arbitrary character c. It cancels the special meaning of characters
( ) . % + - * ? [ ] ^ $
Alternation (expressed in other regex languages using |
)
is not available in Lua; it can only be approximated using [class]
constructions.
Two of the nifty primitives that Lua has and other engines lack are:
%b()
Text inside (and including) balanced(...)
; other characters can be used in place of(
and)
.%f[class]
The zero-width "frontier" between (the start-of-source or) text not matching class and (the end-of-source or) text which does match class. This is a generalization of the Gnu regex specials\<
and\>
. Examples:%f[%x] matches the source text "123-567 9ab" before positions 1, 5, and 9 %f[%X] matches the same source text before positions 4, 8, and 12.