Reputation: 121
Im trying to find files that are looking like this:
access_log-20160101
access_log-20160304
...
with perl regex i came up with something like this:
/^access_log-\d{8}$/
But im not sure about the "_" and the "-". are these metacharacter? What is the expression for this?
i read that "_" in regex is something like \w, but how do i use them in my exypression?
/^access\wlog-\d{8}$/ ?
Upvotes: 1
Views: 984
Reputation: 22421
Underscore (_
) is not a metacharacter and does not need to be quoted (though it won't change anything if you quote it).
Hyphen (-
) IS a metacharacter that defines the range between two symbols inside a bracketed character class. However, in this particular position, it will be interpreted verbatim and doesn't need quoting since it is not inside []
with a symbol on both sides.
You can use your regexp as is; hyphens (-
) might need quoting if your format changes in future.
Upvotes: 3
Reputation: 126722
Your regex pattern is exactly right
Neither underscore _
nor hyphen -
need to be escaped. Outside a square-bracketed character class, the twelve Perl regex metacharacters are
(
)
[
{
*
+
?
^
$
|
.
\
and only these must be escaped
If the pattern of your file names doesn't vary from what you have shown then the pattern that you are using
^access_log-\d{8}$
is correct, unless you need to validate the date string
Within a character class like [A-F]
you must escape the hyphen if you want it to be interpreted literally. As it stands, that class is the equivalent to [ABCDEF]
. If you mean just the three characters A
, -
or F
then [A\-F]
will do what you want, but it is usual to put the hyphen at the start or end of the class list to make it unambiguous. [-AF]
and [AF-]
are the same as [A\-F]
and rather more readable
Upvotes: 3