case insensitive replace
string manipulation
text processing
programming
case sensitivity

Case insensitive replace

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Case insensitive string replacement is a common operation in text processing. The standard replace function in most languages is case sensitive by default, meaning replacing "cat" will not match "Cat" or "CAT". This article shows how to perform case insensitive replacements in Python, JavaScript, Java, C#, and Go, along with edge cases you need to handle.

The Core Problem

Consider this scenario: you have user-generated content and need to replace all variations of a word regardless of capitalization. Searching for "error" should also match "Error", "ERROR", and "eRRoR". A simple str.replace("error", "warning") will miss all of those variants.

The solution depends on the language. Most approaches use either regex with a case-insensitive flag or manual case normalization.

Python: Using re.sub

Python's re.sub function with the re.IGNORECASE flag is the cleanest approach:

python
1import re
2
3text = "The Error was a critical ERROR. Report each error to support."
4result = re.sub(r"error", "warning", text, flags=re.IGNORECASE)
5print(result)
6# Output: The warning was a critical warning. Report each warning to support.

If the search term contains special regex characters, escape them first:

python
1import re
2
3def case_insensitive_replace(text, old, new):
4    pattern = re.compile(re.escape(old), re.IGNORECASE)
5    return pattern.sub(new, text)
6
7result = case_insensitive_replace("Price is $100 (USD)", "(usd)", "[US Dollars]")
8print(result)
9# Output: Price is $100 [US Dollars]

The re.escape call is critical. Without it, characters like (, ), ., and * in the search term would be interpreted as regex metacharacters.

JavaScript: Regex with the i Flag

JavaScript's String.replace accepts a regex with the i (case insensitive) and g (global) flags:

javascript
1const text = "The Error was a critical ERROR. Report each error to support.";
2const result = text.replace(/error/gi, "warning");
3console.log(result);
4// Output: The warning was a critical warning. Report each warning to support.

For dynamic search terms where you cannot use a regex literal, construct a RegExp object:

javascript
1function caseInsensitiveReplace(text, search, replacement) {
2  const escaped = search.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3  const regex = new RegExp(escaped, "gi");
4  return text.replace(regex, replacement);
5}
6
7const result = caseInsensitiveReplace(
8  "Use foo.bar() or FOO.BAR() to initialize",
9  "foo.bar()",
10  "init()"
11);
12console.log(result);
13// Output: Use init() or init() to initialize

Java: Pattern.CASE_INSENSITIVE

Java does not have a built-in case insensitive replace on String, but Pattern with CASE_INSENSITIVE handles it:

java
1import java.util.regex.Pattern;
2
3public class CaseInsensitiveReplace {
4    public static String replace(String text, String search, String replacement) {
5        String escaped = Pattern.quote(search);
6        Pattern pattern = Pattern.compile(escaped, Pattern.CASE_INSENSITIVE);
7        return pattern.matcher(text).replaceAll(replacement);
8    }
9
10    public static void main(String[] args) {
11        String result = replace(
12            "Hello WORLD, hello World, hElLo world",
13            "hello",
14            "goodbye"
15        );
16        System.out.println(result);
17        // Output: goodbye WORLD, goodbye World, goodbye world
18    }
19}

Pattern.quote wraps the search string so that any special regex characters are treated as literals.

C#: Regex.Replace with RegexOptions

C# provides Regex.Replace with RegexOptions.IgnoreCase:

csharp
1using System.Text.RegularExpressions;
2
3string text = "The Server responded. The SERVER is healthy. Check server logs.";
4string result = Regex.Replace(text, Regex.Escape("server"), "host",
5    RegexOptions.IgnoreCase);
6Console.WriteLine(result);
7// Output: The host responded. The host is healthy. Check host logs.

For frequent replacements, compile the regex to avoid repeated pattern parsing:

csharp
var pattern = new Regex(Regex.Escape("server"), RegexOptions.IgnoreCase | RegexOptions.Compiled);
string result = pattern.Replace(text, "host");

Go: strings.NewReplacer Does Not Support Case Insensitivity

Go's standard library does not have a built-in case insensitive replace. Use the regexp package:

go
1package main
2
3import (
4    "fmt"
5    "regexp"
6)
7
8func caseInsensitiveReplace(text, search, replacement string) string {
9    pattern := regexp.MustCompile("(?i)" + regexp.QuoteMeta(search))
10    return pattern.ReplaceAllString(text, replacement)
11}
12
13func main() {
14    result := caseInsensitiveReplace(
15        "Use Config or CONFIG or config",
16        "config",
17        "settings",
18    )
19    fmt.Println(result)
20    // Output: Use settings or settings or settings
21}

The (?i) prefix enables case insensitive matching in Go's regex syntax.

Preserving Original Case

Sometimes you want to replace a word but keep the original capitalization pattern. For example, replacing "cat" with "dog" should turn "Cat" into "Dog" and "CAT" into "DOG":

python
1import re
2
3def case_preserving_replace(text, old, new):
4    def replace_match(match):
5        original = match.group()
6        if original.isupper():
7            return new.upper()
8        if original[0].isupper():
9            return new.capitalize()
10        return new.lower()
11
12    pattern = re.compile(re.escape(old), re.IGNORECASE)
13    return pattern.sub(replace_match, text)
14
15result = case_preserving_replace("The Cat sat. The CAT slept. A cat played.", "cat", "dog")
16print(result)
17# Output: The Dog sat. The DOG slept. A dog played.

Common Pitfalls

Not escaping regex metacharacters. If your search term contains characters like ., (, ), *, or +, they will be interpreted as regex patterns instead of literal characters. Always use re.escape (Python), Pattern.quote (Java), Regex.Escape (C#), or a manual escape function (JavaScript, Go).

Unicode case folding. Simple lowercasing does not handle all Unicode cases correctly. For example, the German sharp s (double-s) uppercases to "SS". If you need full Unicode case folding, use re.UNICODE in Python or Pattern.UNICODE_CASE in Java.

Performance with large texts. Compiled regex is significantly faster than creating a new pattern on each call. If you are performing the same replacement across thousands of strings, compile the pattern once and reuse it.

Replacing partial words unintentionally. Replacing "is" case insensitively in "This island is isolated" will produce "Th warning land warning warning olated" if you are not careful. Use word boundary anchors (\b) to match whole words only.

Summary

Case insensitive replacement requires regex with a case-insensitive flag in most languages. Always escape the search term to prevent regex metacharacter issues. Use re.IGNORECASE in Python, the /gi flags in JavaScript, Pattern.CASE_INSENSITIVE in Java, RegexOptions.IgnoreCase in C#, and (?i) in Go. For repeated replacements, compile the regex pattern once. When matching whole words only, add word boundary anchors to avoid partial matches.


Course illustration
Course illustration

All Rights Reserved.