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?
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.
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.
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.
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, <hello world >")
will return hello a & b, <hello world >
.
HttpUtility.HtmlEncode("hello a & b, <hello world >")
will return hello a & b, <hello world >
You could use regex, I suppose:
Regex.Replace("hello a & b, <hello world >", "&(?![a-z]{1,};)", "&");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With