sceiler
sceiler

Reputation: 1205

How to replace all instances of a sequence of chars inside a string

Assuming I have a text file with the following content:

longtextwith some space and unicode escape like this \u003ca

I want to replace all instances / occurences / sequences of \u003c ignoring the fact that an a is trailing. Something like "look for all instances of a sequence of characters, ignore cases and replace it".

I tried this already but nothing happens:

using (var sr = new StreamReader("1.txt"))
{
    string result = sr.ReadToEnd();

    result = Regex.Replace(result, @"\b\\u003c\b", "<", RegexOptions.IgnoreCase);
}

This variants also yielded not my intended result:

result = Regex.Replace(result, @"\\u003c", "<", RegexOptions.IgnoreCase);
result = Regex.Replace(result, "\u003c", "<", RegexOptions.IgnoreCase);
result = Regex.Replace(result, "\b\\u003c\b", "<", RegexOptions.IgnoreCase);

In Lua this works: str = string.gsub(str, '\\u003e', '>')

In this case I am not interested in the options provided by .NET framework for encoding and decoding of unicode, ascii etc.

Upvotes: 0

Views: 1722

Answers (2)

cbr
cbr

Reputation: 13652

Why not use String.Replace?

string str = inputString.Replace("\\u003c", "<");

If you want a case-insensitive replace, try this:

var regex = new Regex(@" \\u003c", RegexOptions.IgnoreCase);
string str = regex.Replace(inputString, "<");

Upvotes: 2

j2associates
j2associates

Reputation: 1155

Your pattern should be @"\b\u003c". Since you defined it with @, you do not need a double backslash in front of the u003c. Also, \b means a word boundary, so your current pattern will not match a trailing a because it is not then on a word boundary.

For further reference, check out the RegEx.Escape method which helps to ensure your pattern is properly escaped. If you are working with Regular Expressions very often, do yourself a favor and check out www.RegExBuddy.com. I purchased it several years ago and love it. It is a great tool and inexpensive to boot.

Upvotes: 1

Related Questions