grep -P to allow PCRE
Regular expressions are a series of characters that define patterns to search for in text.
- Basic Usage
- Single characters
A
1
\t
- Multiple characters
[abc]
[157]
- Ranges
[a-z]
[A-Z]
[a-zA-Z]
- Any character except line terminators
.
- NOT
How would I match consonants?
[b-df-hj-np-tv-z]
vs[^aeiou]
[^2-8]
- Escaping characters
\.
\[
- Single characters
- Meta-sequences
\s and \S whitespace
\d and \D digits
\w and \W word characters [a-zA-Z1-9_]
- Phone number checker WITHOUT quantifiers
-
Form to match:
123-456-7890
-
Answer!
\d\d\d-\d\d\d-\d\d\d\d
-
- Quantifiers (remember they need to go outside the brackets)
? Zero or one
* Zero or more
+ One or more
{3} Exactly 3
{3,} 3 or more
{,3} At most 3, zero included
{3,6} Between 3-6 times, inclusive
- Phone number checker WITH quantifiers
-
Form to match:
123-456-7890
-
Answer!
\d{3}-\d{3}-\d{4}
-
Form to match: Same but with optional US country code at beginning
1123-456-7890
-
Answer!
1?\d{3}-\d{3}-\d{4}
-
- Anchors
^
Beginning of line$
End of line
- Groups
- So far you could only quantify single characters at a time. You can quantify whole groups.
[123]+ vs (123)+
- So far you could only quantify single characters at a time. You can quantify whole groups.