wisconsin
Regular Expressions

Regular Expressions

Curated by Last modified: 2 min read

Regular Expressions (RegEx) are a language agnostic way to describe patterns in strings. They are used for searching, matching, and manipulating text. Regular expressions can be used in many programming languages, including Python, JavaScript, and Java.

Fun Fact

Regular Expressions were developed by Stephen Cole Kleene, a professor of mathematics at the University of Wisconsin-Madison, in the 1950s.

Character Matching

Regular expressions use special characters to define patterns. Here are some common characters and their meanings:

CharacterDescription
.Matches any single character except a newline.
\dMatches any digit (equivalent to [0-9]).
\DMatches any non-digit character (equivalent to [^0-9]).
\wMatches any word character (alphanumeric and underscore).
\WMatches any non-word character.
\sMatches any whitespace character (spaces, tabs, newlines).
\SMatches any non-whitespace character.

Any character that is not a special character is treated as a literal character. For example, the regex a matches the character a in the string apple.

Combinations

You can combine characters and special characters to create more complex patterns. Here are some common combinations:

CombinationDescription
P1|P2Matches either P1 or P2.
(P)Consider P as a single group.

Quantifiers

Quantifiers are used to specify how many times a character or group should be matched. Here are some common quantifiers:

QuantifierDescription
*Matches 0 or more occurrences of the preceding character.
+Matches 1 or more occurrences of the preceding character.
?Matches 0 or 1 occurrence of the preceding character.
{n}Matches exactly n occurrences of the preceding character.
{n,}Matches n or more occurrences of the preceding character.
{n,m}Matches between n and m occurrences of the preceding character.

Anchors

Anchors are used to specify the position of a match within a string. Essentially, they match a zero-length position between characters in a string.

AnchorDescription
^Matches the start of a string.
$Matches the end of a string.
\bMatches a word boundary (the position between a word and a non-word character).

Using Regular Expressions

In Java, you can use the java.util.regex package to work with regular expressions, which provides classes like Pattern and Matcher.

In the terminal, you can use grep (Global Regular Expression Print) to search for patterns in files. The -E option enables extended regular expressions, and the -o option prints only the matched parts of the lines.

Connections

Obvious technical and formatting errors repaired.

Linked to this page