Match Text Before a Pattern with Regex
How to match the text that comes before a delimiter or pattern with regex: lookahead, capture groups and negated classes, engine support, Unicode pitfalls, and when plain string methods are the better choice.
Pulling out everything that appears before a delimiter, keyword or file extension is one of the most common regex jobs. Several patterns do it, and they differ in what they return when the delimiter is missing, which engines support them, and how they handle Unicode text. This review explains each approach so you can judge whether it fits your use, and points out when a plain string method is simpler and safer.
Is a regex the right tool for this?
Use a regex when the boundary is a pattern rather than a fixed character, for example a run of digits, one of several keywords, or a delimiter only at the end of the line. The decisive tradeoff is that small differences in the pattern change the result. Greedy and lazy quantifiers stop at different occurrences. Lookahead and capture-group versions behave differently when the delimiter is absent. Some engines reject lookaround syntax entirely.
If the boundary is a single fixed string, such as the first colon or the first equals sign, a plain string method is usually preferable. Python's str.partition or str.split with a limit and JavaScript's indexOf with slice are easier to read and have no quantifier surprises. They also make the missing-delimiter case explicit.
What "match before" actually does
Matching text before a pattern does not change the stored text. A search returns a span or a captured group from the original string, and the input stays as it was. Only a replace operation produces new text. That separates it from transformations such as string reversal, mirrored glyphs or Unicode font substitution, which do change characters or how they appear.
There are three common ways to express "text before X":
- Lookahead: .*?(?=X) matches characters up to the point where X begins. X itself is checked but not included in the match.
- Capture group: (.*?)X matches through X, and you read only group 1.
- Negated character class: [^X]* matches a run of characters that are not X. This works only when X is a single character, and it needs no lookaround support.
A common point of confusion is that lookbehind, written (?<=X), is the wrong tool here. It asserts that X comes before the current position, so it matches text after X. To match text before X, use lookahead or a capture group.
Worked examples
Each example below can be traced by hand. Results are as written for the stated input.
Input: key=value=more
^.*(?==) -> key=value (greedy: stops before the LAST '=')
^.*?(?==) -> key (lazy: stops before the FIRST '=')
^[^=]* -> key (negated class, no lookahead)
Input: novalue (no '=' present)
^.*?(?==) -> no match
^[^=]* -> novalue (matches the whole string)
The last pair shows the main behavioral difference. The lookahead form requires the delimiter, while the negated-class form treats a missing delimiter as "everything is before it." Decide which behavior your data needs before choosing a pattern.
# Python
import re
m = re.search(r'^(.*?):', 'Content-Type: text/plain')
m.group(1) # 'Content-Type'
'Content-Type: text/plain'.partition(':')[0] # 'Content-Type' (no regex)
// JavaScript
'Content-Type: text/plain'.match(/^.*?(?=:)/)[0] // 'Content-Type'
# File name without a trailing .pdf extension
^.*?(?=\.pdf$) on invoice-2041.pdf -> invoice-2041
Two details are easy to miss. First, a dot does not match a newline by default in most engines, so the patterns above stop at the end of a line unless you enable a dotall or single-line flag. Second, the anchor ^ matters. Without it, a search can start partway through the string and return a shorter span than you expect.
Engine support and portability
A pattern that works in one tester may fail elsewhere. The table summarizes documented support in widely used engines. Exact limits can vary by version, so check the documentation for the version you deploy.
| Engine | Lookahead (?=...) | Lookbehind (?<=...) | \K reset |
| JavaScript (ES2018 and later) | Yes | Yes | No |
| Python re | Yes | Fixed width only | No |
| PCRE (PHP preg, grep -P) | Yes | Length-restricted | Yes |
| Java | Yes | Bounded length | No |
| .NET | Yes | Yes | No |
| Go regexp (RE2) | No | No | No |
| POSIX ERE (grep -E, sed -E) | No | No | No |
In engines without lookaround, use the capture-group or negated-class forms. Go's regexp supports lazy quantifiers, so ^(.?)X with the first submatch works. With sed, you can delete the delimiter and everything after it. For example, sed 's/=.//' turns key=value=more into key, because the match starts at the leftmost '='.
Unicode and the string-reversal workaround
Older advice sometimes suggests reversing a string so that a lookbehind problem becomes a lookahead problem, then reversing the result back. That trick is not needed for matching text before a pattern. It is also unsafe for general text. Reversing by code units or code points separates combining marks from their base letters. A decomposed é (an e followed by U+0301) reversed this way leaves the accent at the front with nothing to attach to. Multi-code-point emoji, such as zero-width-joiner sequences and flags, also break into fragments, and in JavaScript, splitting a string with split('') breaks surrogate pairs. If you ever need to reverse user-visible text, reverse by grapheme cluster, for example with Intl.Segmenter in JavaScript.
Character classes also differ by engine. In JavaScript, \w and \b are ASCII-only, so a pattern meant to stop before a word can misfire on accented or non-Latin letters. In Python 3, the same classes are Unicode-aware for str patterns. Test with representative non-ASCII input if your data contains it.
Will the pattern and its results survive copying and sharing?
The extracted text is an ordinary substring of the input, so it copies and pastes as plain text. Reading order, search and screen-reader behavior are the same as for the original. Problems usually come from the pattern itself, not the result.
- Escaping: a pattern copied from a tester into source code may need doubled backslashes, or a raw string such as Python's r'...'. In a shell it needs quoting, often single quotes, so that the shell does not interpret $, * or backslashes.
- Invisible characters: text copied from web pages or documents can contain non-breaking spaces, curly quotes or zero-width characters. These look identical to plain ones but will not match a pattern written with ordinary spaces or quotes.
- Flavor drift: a pattern that passes in an online tester set to one flavor can fail in an engine from the table above. Confirm that the tester's flavor matches your runtime.
- Readability for others: regex is hard to read aloud or skim. When you share a pattern in documentation or code review, add a one-line plain-language description of what it returns, including the missing-delimiter case.
Gaps in this review
No tool-specific evidence was supplied for this article. It does not evaluate any particular online regex tester, and it makes no claims about a tester's privacy, data retention or rendering. The engine notes reflect general documented behavior, not tests run for this piece. Verify them against your runtime version, especially lookbehind limits, which have changed across releases in some engines.
Recommendation
For a single fixed delimiter, use a string method, or [^X]* if you are already in a regex context. For a pattern-shaped boundary, use a lazy lookahead such as ^.?(?=X) when your engine supports it, or a capture group such as ^(.?)X when it does not. Choose deliberately between "no match" and "whole string" for input without the delimiter. Avoid the string-reversal workaround for any text that may contain accents or emoji.