Is There an Alternative to String.Replace That Is Case-Insensitive

String.Replace ignoring case

You could use a Regex and perform a case insensitive replace:

class Program
{
static void Main()
{
string input = "hello WoRlD";
string result =
Regex.Replace(input, "world", "csharp", RegexOptions.IgnoreCase);
Console.WriteLine(result); // prints "hello csharp"
}
}

Is there an alternative to string.Replace that is case-insensitive?

From MSDN

$0 - "Substitutes the last substring matched by group number number (decimal)."

In .NET Regular expressions group 0 is always the entire match. For a literal $ you need to

string value = Regex.Replace("%PolicyAmount%", "%PolicyAmount%", @"$$0", RegexOptions.IgnoreCase);

How to ignore case in String.replace

Use a regular expression:

var regex = new Regex( "camel", RegexOptions.IgnoreCase );
var newSentence = regex.Replace( sentence, "horse" );

Of course, this will also match words containing camel, but it's not clear if you want that or not.

If you need exact matches you can use a custom MatchEvaluator.

public static class Evaluators
{
public static string Wrap( Match m, string original, string format )
{
// doesn't match the entire string, otherwise it is a match
if (m.Length != original.Length)
{
// has a preceding letter or digit (i.e., not a real match).
if (m.Index != 0 && char.IsLetterOrDigit( original[m.Index - 1] ))
{
return m.Value;
}
// has a trailing letter or digit (i.e., not a real match).
if (m.Index + m.Length != original.Length && char.IsLetterOrDigit( original[m.Index + m.Length] ))
{
return m.Value;
}
}
// it is a match, apply the format
return string.Format( format, m.Value );
}
}

Used with the previous example to wrap the match in a span as:

var regex = new Regex( highlightedWord, RegexOptions.IgnoreCase );
foreach (var sentence in sentences)
{
var evaluator = new MatchEvaluator( match => Evaluators.Wrap( match, sentence, "<span class='red'>{0}</span>" ) );
Console.WriteLine( regex.Replace( sentence, evaluator ) );
}

Case-insensitive string replace-all in JavaScript without a regex

  1. Start with an empty string and copy the original string.
  2. Find the index of the string to replace in the copy (setting them both to lowercase makes the search case-insensitive).
  3. If it's not in the copy, skip to step 7.
  4. Add everything from the copy up to the index, plus the replacement.
  5. Trim the copy to everything after the part you're replacing.
  6. Go back to step 2.
  7. Add what's left of the copy.

Just for fun I've created an interactive version where you can see the results of both a regex and indexOf, to see if escaping a regex breaks anything. The method used to escape the regex I took from jQuery UI. If you have it included on the page it can be found with $.ui.autocomplete.escapeRegex. Otherwise, it's a pretty small function.

Here's the non-regex function, but since the interactive section adds a lot more code I have the full code snippet hidden by default.

function insensitiveReplaceAll(original, find, replace) {
var str = "",
remainder = original,
lowFind = find.toLowerCase(),
idx;

while ((idx = remainder.toLowerCase().indexOf(lowFind)) !== -1) {
str += remainder.substr(0, idx) + replace;

remainder = remainder.substr(idx + find.length);
}

return str + remainder;
}

// example call:
insensitiveReplaceAll("Find aBcc&def stuff ABCabc", "abc", "ab");

function insensitiveReplaceAll(original, find, replace) {  var str = "",    remainder = original,    lowFind = find.toLowerCase(),    idx;
while ((idx = remainder.toLowerCase().indexOf(lowFind)) !== -1) { str += remainder.substr(0, idx) + replace;
remainder = remainder.substr(idx + find.length); }
return str + remainder;}
function escapeRegex(value) { return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");}
function updateResult() { var original = document.getElementById("original").value || "", find = document.getElementById("find").value || "", replace = document.getElementById("replace").value || "", resultEl = document.getElementById("result"), regexEl = document.getElementById("regex");
if (original && find && replace) { regexEl.value = original.replace(new RegExp(escapeRegex(find), "gi"), replace); resultEl.value = insensitiveReplaceAll(original, find, replace); } else { regexEl.value = ""; resultEl.value = ""; }

}
document.addEventListener("input", updateResult);window.addEventListener("load", updateResult);
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<div class="input-group input-group-sm"> <span class="input-group-addon">Original</span> <input class="form-control" id="original" value="Find aBcc&def stuff ABCabc" /></div>
<div class="input-group input-group-sm"> <span class="input-group-addon">Find</span> <input class="form-control" id="find" value="abc" /></div>
<div class="input-group input-group-sm"> <span class="input-group-addon">Replace</span> <input class="form-control" id="replace" value="ab" /></div>
<div class="input-group input-group-sm"> <span class="input-group-addon">Result w/o regex</span> <input disabled class="form-control" id="result" /></div>
<div class="input-group input-group-sm"> <span class="input-group-addon">Result w/ regex</span> <input disabled class="form-control" id="regex" /></div>

How to do a case-insensitive string replacement

Could use a regular expression.
Just add (?i) before your string to ignore case.

So for example:

multiword.getString().replaceAll ( "(?i)radha", "sai");

Is there a case insensitive string replace in .Net without using Regex?

Found one in the comments here: http://www.codeproject.com/Messages/1835929/this-one-is-even-faster-and-more-flexible-modified.aspx

static public string Replace(string original, string pattern, string replacement, StringComparison comparisonType)
{
return Replace(original, pattern, replacement, comparisonType, -1);
}

static public string Replace(string original, string pattern, string replacement, StringComparison comparisonType, int stringBuilderInitialSize)
{
if (original == null)
{
return null;
}

if (String.IsNullOrEmpty(pattern))
{
return original;
}

int posCurrent = 0;
int lenPattern = pattern.Length;
int idxNext = original.IndexOf(pattern, comparisonType);
StringBuilder result = new StringBuilder(stringBuilderInitialSize < 0 ? Math.Min(4096, original.Length) : stringBuilderInitialSize);

while (idxNext >= 0)
{
result.Append(original, posCurrent, idxNext - posCurrent);
result.Append(replacement);

posCurrent = idxNext + lenPattern;

idxNext = original.IndexOf(pattern, posCurrent, comparisonType);
}

result.Append(original, posCurrent, original.Length - posCurrent);

return result.ToString();
}

Should be the fastest, but i haven't checked.

Otherwise you should do what Simon suggested and use the VisualBasic Replace function. This is what i often do because of its case-insensitive capabilities.

string s = "SoftWare";
s = Microsoft.VisualBasic.Strings.Replace(s, "software", "hardware", 1, -1, Constants.vbTextCompare);

You have to add a reference to the Microsoft.VisualBasic dll.

Multiple case insensitive strings replacement

You can try to use regex to archive it

Example

String str = "Dang DANG dAng dang";
//replace all dang(ignore case) with Abhiskek
String result = str.replaceAll("(?i)dang", "Abhiskek");
System.out.println("After replacement:" + " " + result);

Result:

After replacement: Abhiskek Abhiskek Abhiskek Abhiskek

EDIT


String[] old = {"ABHISHEK","Name"};
String[] nw = {"Abhi","nick name"};
String s="My name is Abhishek";
//make sure old and nw have same size please
for(int i =0; i < old.length; i++) {
s = s.replaceAll("(?i)"+old[i], nw[i]);
}
System.out.println(s);

Result:

My nick name is Abhi

Basic ideal: Regex ignore case and replaceAll()

From the comment @flown (Thank you) you need to use

str.replaceAll("(?i)" + Pattern.quote(old[i]), nw[i]);

Because regex treats some special character with a different meaning, ex: . as any single character

So using the Pattern.quote will do this.

How to replace case-insensitive literal substrings in Java

String target = "FOOBar";
target = target.replaceAll("(?i)foo", "");
System.out.println(target);

Output:

Bar

It's worth mentioning that replaceAll treats the first argument as a regex pattern, which can cause unexpected results. To solve this, also use Pattern.quote as suggested in the comments.

Case insensitive string replacement in JavaScript?

You can use regular expressions if you prepare the search string. In PHP e.g. there is a function preg_quote, which replaces all regex-chars in a string with their escaped versions.

Here is such a function for javascript (source):

function preg_quote (str, delimiter) {
// discuss at: https://locutus.io/php/preg_quote/
// original by: booeyOH
// improved by: Ates Goral (https://magnetiq.com)
// improved by: Kevin van Zonneveld (https://kvz.io)
// improved by: Brett Zamir (https://brett-zamir.me)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// example 1: preg_quote("$40")
// returns 1: '\\$40'
// example 2: preg_quote("*RRRING* Hello?")
// returns 2: '\\*RRRING\\* Hello\\?'
// example 3: preg_quote("\\.+*?[^]$(){}=!<>|:")
// returns 3: '\\\\\\.\\+\\*\\?\\[\\^\\]\\$\\(\\)\\{\\}\\=\\!\\<\\>\\|\\:'

return (str + '')
.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&')
}

So you could do the following:

function highlight(str, search) {
return str.replace(new RegExp("(" + preg_quote(search) + ")", 'gi'), "<b>$1</b>");
}

C# Replace string case insensitive

If the answer from the duplicate question does't help you, here is the code in your case (notice I removed the while loop - the condition in it is false if casing is different and also you don't really need it):

foreach (string fWord in FilteredWords)
{
Input = Regex.Replace(Input, fWord, "****", RegexOptions.IgnoreCase);
}

For example, the code below

string fWord = "abc";
input = "AbC";
input = Regex.Replace(input, fWord, "****", RegexOptions.IgnoreCase);

produces the value ****.



Related Topics



Leave a reply



Submit