Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a character in C# string ignoring other characters?

Tags:

c#

Consider that I have a following string:

string s = "hello a & b, <hello world >" 

I want to replace "&" (b/w a and b) with "&"

So, if I use

s.replace("&", "&"); 

It will also replace "&" associated with < and >.

Is there any way I can replace only "&" between a and b?

like image 208
KP Joy Avatar asked Aug 24 '20 04:08

KP Joy


People also ask

How do I replace a character?

The Java String class replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence. Since JDK 1.5, a new replace() method is introduced that allows us to replace a sequence of char values.

How do you replace a specific character in a string?

Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do I replace a character in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.


2 Answers

You can rather use HttpUtility.HtmlEncode & HttpUtility.HtmlDecode like below.

First decode your string to get normal string and then encode it again which will give you expected string.

HttpUtility.HtmlEncode(HttpUtility.HtmlDecode("hello a & b, <hello world >")); 
  • HttpUtility.HtmlDecode("hello a & b, &lt;hello world &gt;") will return hello a & b, <hello world >.

  • HttpUtility.HtmlEncode("hello a & b, <hello world >") will return hello a &amp; b, &lt;hello world &gt;

like image 69
Karan Avatar answered Oct 24 '22 04:10

Karan


You could use regex, I suppose:

Regex.Replace("hello a & b, &lt;hello world &gt;", "&(?![a-z]{1,};)", "&amp;"); 
  • & match literal &
  • (?! ) negative lookahead (assert that the following does not match)
  • [a-z]{1,}; any char a-z, one or more times, followed by a single ';'
like image 29
afrischke Avatar answered Oct 24 '22 04:10

afrischke