Regex Flashcards
How to find a plain string?
Just use the string.
i.e. abc finds abc in a file
Note that grep finds each line that contains this.
How to include spaces in a regex search?
You need to need single or double quotation marks.
Anchoring in regex
Use ^ to match for the beginning.
i.e.
^abc finds strings that start with abc
Use $ to match for the end
i.e.
abc$ finds strings that end with abc
Note that these can be combined.
i.e.
^abc$ finds lines that only contain abc
How to regex for empty lines?
^$
How to match a single character?
Use .
For example:
m..t
could find malt, meet, moot…
What is a bracket expression?
Allow matching of characters by enclosing them in []
For example:
acce[np]t would fines lines containing accent and accept
How to do a bracket expression that excludes certain characters?
Use ^ at the beginning of the expression.
i.e.
co[^l]a
would find coca, cobalt, but not cola.
How to specify a range of characters?
Inside of the brackets, use a - to connect the beginning and end.
i.e.
[1-9] is equivalent to [123456789]
[a-e] is equivalent to [abcde]
How to find some type/group of characters?
Use the predefined classes.
I.e.
[:alnum:]
Alphanumeric class
:alnum:
Alphabetic class
:alpha:
Spaces and tabs class
:blank:
Digit class
:digit:
Lowercase letters class
:lower:
Uppercase letters class
:upper:
What is a quantifier?
Allows you to specify the number of occurrences that must be present to match.
*
?
+
{n}
{n,}
{,m}
{n,m}
Note that this works on the PRECEEDING character.
How to match 0 or more times?
*
How to match 0 or 1 time?
?
How to match 1 or more times?
+
How to match exactly n times?
{n}
How to match at least n times?
{n,}
How to match at most m times?
{,m}
How to match n to m times?
{n,m}
How to include a regex symbol as a string so that it is not interpreted as regex?
Use an escape character.
How to match different possible matches?
Use |
For example, ‘big|large|massive’ matches big, OR large, OR massive.
Note that using -E for extended regular expressions, \ can be omitted (don’t escape |).
How to group things?
Use brackets. Note, must use \ on parenthesis when not using extended regex.
For example ‘(fear)?less’ finds lines that include less preceded by 1 or 0 fear.
Special backslash expressions.
\b matches a word boundary
< matches an empty string at the beginning of a word
> matches an empty string at the end of a word
\w matches a word
\s matches a space
For example,
‘\bhello\b’ finds hello, but not if it is embedded in a larger word.