Summary: in this tutorial, you will learn about the C# regex lookbehind to match a pattern only if it is preceded by another pattern.
Introduction to the C# regex lookbehind
Regex lookbehind allows you to specify a pattern to match only if it is preceded by another pattern. In simple terms, a regex lookbehind matches A only if it is preceded by B:
(?<=B)A
Code language: C# (cs)
The following example shows how to use a lookbehind to match a number that is followed by a $
sign:
using System.Text.RegularExpressions;
using static System.Console;
var text = "10 books cost $200";
var pattern = @"\b(?<=\$)\d+\b";
var matches = Regex.Matches(text, pattern);
foreach (var match in matches)
{
WriteLine(match);
}
Code language: C# (cs)
Output:
200
Code language: C# (cs)
In this example, we use the (?<=\$)\d+
regular expression pattern that contains a look behind:
\b
is a word boundary , the\b...\b
matches the whole word.(?<=\$)
is a lookbehind that checks if the current position is preceded by a dollar sign ($
) character. Because$
is a metacharacter in a regular expression, we need to escape it using a backslash character (\
) so that$
will be treated as a literal string.\d+
is a digit character class that matches one or more digits.
Negative lookbehind
A negative lookbehind negates a lookbehind. In other words, a negative lookbehind allows you to specify a pattern to match only if it is not preceded by another pattern:
(?<!B)A
Code language: C# (cs)
In this syntax, the regular expression matches A
if it is not preceded by B
. Note that !
is used instead of =
character.
The following example uses a negative lookbehind to match the number 10
in an input string, not the number 200
that is preceded by the $
sign:
using System.Text.RegularExpressions;
using static System.Console;
var text = "10 books cost $200";
var pattern = @"\b(?<!\$)\d+\b";
var matches = Regex.Matches(text, pattern);
foreach (var match in matches)
{
WriteLine(match);
}
Code language: C# (cs)
Output:
10
Code language: C# (cs)
Summary
- Use regex lookbehind to match a pattern that is preceded by another pattern.
- Use a negative lookbehind to match a pattern that is not preceded by another pattern.