How to Clean Messy Data with Regex
Published · 5 min read
Real data arrives untidy. Exported spreadsheets carry stray spaces, copied web text drags HTML tags along, and the same date shows up in three formats in one column. Regex find-and-replace is one of the fastest ways to fix this, whether you work in a text editor, a spreadsheet tool, JavaScript or Python. This guide collects the recipes that come up most often, explains each pattern, and is clear about where a dedicated parser is the better choice.
How replacement with groups works
Most of the recipes below capture part of the match with parentheses and reuse it in the replacement. In JavaScript, and in most editors, the first group is written $1, the second $2, and so on. Python uses \1 or \g<1> instead. A quick example that swaps "Test, Ali" into "Ali Test":
"Test, Ali".replace(/^(\w+),\s*(\w+)$/, "$2 $1"); // "Ali Test"If capture groups are new to you, the replace with groups lesson covers them with live exercises. Everything else in this article builds on that one idea.
When a pattern has several groups, numbered references get hard to read. Named groups help: write (?<day>\d{2}) in the pattern and $<day> in a JavaScript replacement, or \g<day> in Python. The intent stays obvious months later, and adding a new group does not shift every number after it. Also remember that a literal dollar sign in a JavaScript replacement string must be written as $$.
Fixing whitespace
Whitespace problems are the most common and the safest to fix. Three patterns cover nearly all of them:
- Trailing spaces at the end of each line: find
[ \t]+$with the multiline flag, replace with nothing. - Runs of spaces or tabs inside a line: find
[ \t]{2,}, replace with a single space. - Too many blank lines: find
\n{3,}, replace with\n\nto keep at most one empty line between paragraphs.
function tidyWhitespace(text) {
return text
.replace(/\r\n/g, "\n") // normalise Windows line endings
.replace(/[ \t]+$/gm, "") // trailing spaces
.replace(/[ \t]{2,}/g, " ") // repeated spaces and tabs
.replace(/\n{3,}/g, "\n\n") // extra blank lines
.trim();
}Notice that these patterns use [ \t] rather than \s. The shorthand \s also matches line breaks, so \s{2,} would merge separate lines into one. Being specific about which whitespace you mean is a recurring theme in data cleaning; see shorthand classes for what each shorthand covers.
Removing duplicates
Doubled words
Typing errors like "the the" are easy to catch with a backreference, which matches the same text a group captured earlier:
\b(\w+)\s+\1\bReplace with $1 to keep one copy. Add the i flag to also catch "The the". Review the matches before replacing, because some repetitions are intentional, as in "that that" in certain sentences.
Repeated lines
Consecutive identical lines can be collapsed with the multiline flag:
^(.*)(?:\n\1)+$Replace with $1. This only handles duplicates that sit next to each other. To remove duplicates anywhere in a file, regex is the wrong tool: split into lines and use a set, which is simpler and much faster on large files.
lines = text.splitlines()
unique = list(dict.fromkeys(lines)) # keeps the first occurrence, preserves order
result = "\n".join(unique)Normalising dates
Converting DD/MM/YYYY to ISO 8601 YYYY-MM-DD is a classic reordering job. Capture the three parts and write them back in a new order:
\b(\d{2})/(\d{2})/(\d{4})\bimport re
text = "Joined 05/03/2026, left 28/11/2026."
print(re.sub(r"\b(\d{2})/(\d{2})/(\d{4})\b", r"\3-\2-\1", text))
# Joined 2026-03-05, left 2026-11-28.Two warnings. First, the regex cannot know whether 05/03/2026 is the 5th of March or the 3rd of May; you have to know the source format. Second, it does not check that the date exists, so 31/02/2026 converts without complaint. Validate with a date library afterwards. The library has tested patterns for DD/MM/YYYY dates and ISO 8601 dates if you need stricter shapes.
Normalising phone numbers
Phone numbers come with spaces, dashes, brackets and different prefixes. The reliable approach is two steps: strip the decoration, then rebuild one canonical format. For a Pakistani mobile number typed as +92 300 0000000, 0300-0000000 or 03000000000:
function normaliseMobile(input) {
const compact = input.replace(/[\s().-]/g, "");
const m = compact.match(/^(?:\+92|0092|0)(3\d{2})(\d{7})$/);
return m ? `0${m[1]}-${m[2]}` : null;
}
normaliseMobile("+92 300 0000000"); // "0300-0000000"
normaliseMobile("(0300) 000-0000"); // "0300-0000000"Returning null for anything that does not fit is deliberate. A cleaning step should flag rows it cannot handle rather than guess. For other countries, start from the international phone number pattern, and see how to extract phone numbers for finding them inside free text.
Stripping HTML tags
Text copied from web pages or exported from a CMS often contains tags. For simple, trusted fragments this pattern removes them:
<[^>]+>It matches a <, then one or more characters that are not >, then >. The negated set keeps each match inside a single tag, where a lazy .*? would also work. Be aware of the limits: it leaves entities such as & untouched, keeps the text inside script and style elements, and can be fooled by a > inside an attribute value. For anything security-related, such as sanitising user input, use a real HTML parser or sanitiser, never a regex.
Working with CSV fields
CSV looks like it should split on commas, until a field contains one inside quotes. This pattern matches either a quoted field, allowing doubled quotes inside it, or an unquoted run of non-comma characters:
"(?:[^"]|"")*"|[^,]+On Ali Test,"Lahore, PK",42 it finds three fields, keeping the comma inside the quotes intact. It skips empty fields and does not handle line breaks inside quoted values, so treat it as a quick inspection tool. For actual imports, use the CSV module your language provides, such as Python's csv module, and apply regex to the individual field values afterwards.
Smaller fixes worth knowing
A handful of other problems turn up in almost every dataset. Each has a short pattern:
- Invisible characters: non-breaking spaces and zero-width characters often survive copy and paste. Find
[\u00A0\u200B\uFEFF]and replace with a normal space or nothing, depending on the character. - Smart quotes: replace
[\u2018\u2019]with'and[\u201C\u201D]with a straight double quote so later patterns that expect plain quotes still match. - Space before punctuation: find
\s+([,.;:!?])and replace with$1to turn "Lahore , PK" into "Lahore, PK". - Thousands separators in numbers: find
(\d),(?=\d{3}\b)and replace with$1to turn1,250,000into1250000before converting the value to a number.
The last recipe uses a lookahead so that only commas followed by exactly three digits are removed, leaving commas that separate list items alone. Run it only on columns you know are numeric, since it would also change text like "pages 1,234".
Case is another frequent mismatch. Regex alone cannot upper-case a captured group in JavaScript's replace string, but you can pass a function as the replacement and transform the group there, for example capitalising the first letter of each word in a name column.
A cleaning workflow that holds up
- Profile first: search for each problem and count matches before changing anything.
- Fix one issue per pass, from safest (whitespace) to riskiest (reformatting).
- Keep the rules in code, not just in an editor's history, so the cleaning is repeatable.
- Flag rows that do not fit a pattern instead of forcing them into shape.
- Spot-check the output against the original.
You can try every pattern here in the RegexLab tester, which highlights matches and previews replacements as you type, all locally in your browser. If you need a pattern for a format not covered here, the generator can build one from ready-made templates for common formats.
Frequently asked questions
- How do I replace multiple spaces with one using regex?
- Find [ \t]{2,} and replace with a single space. Avoid \s{2,} if you want to keep line breaks, because \s also matches newlines.
- What does $1 mean in a regex replacement?
- It inserts the text captured by the first group of parentheses in the match. $2 inserts the second group, and so on. Python uses \1 or \g<1> instead.
- Can regex safely strip HTML tags?
- For simple, trusted text, <[^>]+> removes tags well enough. It does not decode entities or handle every edge case, so use a proper HTML parser or sanitiser for untrusted input.
- Should I parse CSV files with regex?
- Only for quick inspection. Quoted fields, embedded commas and line breaks inside values are handled correctly by a real CSV parser, so use one for imports and apply regex to individual fields.
Related posts
- How to Extract Anything from Text with RegexA repeatable regex method for pulling codes, emails, dates and amounts out of messy text, with tested patterns and JavaScript and Python code.
- How to Extract Phone Numbers with RegexRegex patterns to find phone numbers in text: local formats, international E.164 numbers and a loose extractor, plus cleanup in JS and Python.
- Regex vs AI: When to Use WhichRegex vs AI for text tasks: determinism, cost, privacy and speed versus flexibility, and how to combine the two safely in real projects.