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"
}
}
Case insensitive replace
The string
type doesn't support this. You're probably best off using the regular expression sub method with the re.IGNORECASE option.
>>> import re
>>> insensitive_hippo = re.compile(re.escape('hippo'), re.IGNORECASE)
>>> insensitive_hippo.sub('giraffe', 'I want a hIPpo for my birthday')
'I want a giraffe for my birthday'
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 ) );
}
How to make string replacements case-insensitive
You can use a stringr::str_replace_all
with a function as a replacement argument, where you can simply remove all whitespaces you want.
See an R demo:
library(stringr)
tst <- c("Wan na go ? well du n no. come on", "i do n't know really",
"will be great in n it, ", "it matters Dun n it",
"Looks awesome. Dun n it?", "Gon na be terrific!")
reduced <- c("in n it", "du n no", "dun n it", "wan na", "gon na", "got ta")
reduced_pattern <- paste0("(?i)\\b(?:", paste0(reduced, collapse = "|"), ")\\b")
str_replace_all(tst, reduced_pattern, function(x) str_replace_all(x, "\\s+",""))
## => [1] "Wanna go ? well dunno. come on" "i do n't know really"
## [3] "will be great innit, " "it matters Dunnit"
## [5] "Looks awesome. Dunnit?" "Gonna be terrific!"
How can I perform a case insensitive replace in JavaScript?
You need to pass <b>$&</b>
as the second parameter to .replace
to insert the matched substring:
const string = "The quick brown fox jumped over the lazy QUICK dog";console.log( string.replace(/quick/gi, '<b>$&</b>'));
Case insensitive replace all
Try regex:
'This iS IIS'.replace(/is/ig, 'as');
Working Example: http://jsfiddle.net/9xAse/
e.g:
Using RegExp object:
var searchMask = "is";
var regEx = new RegExp(searchMask, "ig");
var replaceMask = "as";
var result = 'This iS IIS'.replace(regEx, replaceMask);
Case-insensitive string replace-all in JavaScript without a regex
- Start with an empty string and copy the original string.
- Find the index of the string to replace in the copy (setting them both to lowercase makes the search case-insensitive).
- If it's not in the copy, skip to step 7.
- Add everything from the copy up to the index, plus the replacement.
- Trim the copy to everything after the part you're replacing.
- Go back to step 2.
- 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>
Javascript | case-insensitive string replace
With a case-insensitive regular expression:
function boldString(str, find) { var reg = new RegExp('('+find+')', 'gi'); return str.replace(reg, '<b>$1</b>');}console.log(boldString('Apple', 'ap'))
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 ****
.
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.
Related Topics
Data Scraping from Published Power Bi Visual
What Are the Python Equivalents to Ruby's Bundler/Perl's Carton
Ruby Equivalent of Python's "Dir"
Does Python Have an "Or Equals" Function Like ||= in Ruby
Please Introduce a Multi-Processing Library in Perl or Ruby
Does Ruby Have Something Like Python's List Comprehensions
What Is the "Sys.Stdout.Write()" Equivalent in Ruby
Output Seckeycopyexternalrepresentation
Convert Uiimage from Bgr to Rgb
Differencebetween Ruby and Python Versions Of"Self"
How Can One Find the Unicode Codepoints That a Font Has Glyphs For, on a Debian-Based System
Different Yaml Array Representations
Find in Files Using Ruby or Python
Aes Python Encryption and Ruby Encryption - Different Behaviour
How to Import a JSON from a File on Cloud Storage to Bigquery
How to Parse a Time String Containing Milliseconds in It with Python