C# replace string if string has other characters from both ends - c#

I want to replace a string if it is a part of another string from both ends.
Say for example a string +35343+3566. I want to replace +35 with 0 only if it is surrounded with characters from both sides. So desired outcome would be +35343066.
Normally I'd use line.Replace("+35", "0") and perhaps if-else to meet a condition
string a = "+35343+3566";
string b = a.Replace("+35", "0");
I would want 'b = +35343066 and not b = 0343066`

You can use regex for this. For example:
var replaced = Regex.Replace("+35343+3566", "(?<=.)(\\+35)(?=.)", "0");
// replaced will contain +35343066
So what this pattern is saying is that +35 (\\+35) must have one character behind (?<=.) and one character ahead (?=.)

You can do this with a Regular Expression, as follows:
string a = "+35343+3566";
var regex = new Regex(#"(.)\+35(.)"); // look for "+35" between any 2 characters, while remembering the characters that were found in ${1} and ${2}
string b = regex.Replace(a, "${1}0${2}"); // replace all occurences with "0" surrounded by both characters that were found
See Fiddle: https://dotnetfiddle.net/OdCKsy
Or slightly simpler, if it turns out that only the prefix character matters:
string a = "+35343+3566";
var regex = new Regex(#"(.)\+35"); // look for a character followed by "+35", while remembering the character that was found in ${1}
string b = regex.Replace(a, "${1}0"); // replace all occurences with the character that was found followed by a 0
See Fiddle: https://dotnetfiddle.net/9jEHMN

Related

Replace single slash in string C#

My requirement
If string contains single slash (/ or \) it should be replace with
double slash
Note :- string is randomly generated so, I have no control.
e.g. I have string
string str = #"*?i//y\^Pk#t9`n2";
When I tried as
str = str.Replace(#"\", #"\\").Replace(#"/",#"//");
it replaced // with //// but I need to replace only single slash(\) with double slash(\\).
Above code actual result is
*?i////y\^Pk#t9`n2
expected result is
*?i//y\\^Pk#t9`n2
Note :- If string contain double slash in sequence like "//" or "\\" then no need to modify string. but string contains single slash (/ or \) need to replace with double slash.
I have tried to find out other approach then I found following stack-overflow already question-answer
Replace single backslash with double backslash
Replace "\\" with "\" in a string in C#
How to change backslash to double backslash?
Question :-
How to check if string contain single slash and how to replace it?
What best practice should follows while doing string manipulation like this?
Edit :-
I have random generated string comes from user like.
string str = #"*?i//y\^Pk#t9`n2";
sometimes that string contain single slash as above (\). if we consider above string without verbatim(#) it is not a valid string in C#. it gives compile time error. to make above string valid I need to replace "\" with "\\".
How I can achieve this?
Pls try this, first i repleced all double slash with single slash and then vice versa:
var str = #"*?i//y\^Pk#t9`n2";
var tempStr = str.Replace(#"\\", #"\").Replace(#"//",#"/");
var result = tempStr.Replace(#"\", #"\\").Replace(#"/",#"//");
I had to do two Regex.Replace and use look arounds to achieve this. The final solution was
Regex.Replace(Regex.Replace(str, #"(?<!\/)\/(?!\/)", #"//"), #"(?<!\\)\\(?!\\)", #"\\")
If you've never dealt with regex before, it can be a beast. Essentially I am looking for all backslashes and forward slashes (\\ and \/ escaped) and once I match a backslash and forward slash, I am going to use negative lookbehinds and negative aheads to not match if it there is a match in front or behind it.
Negative Look Behind:
(?<!\/)
Negative Look Ahead:
(?!\/)
I am then repeating it twice for forward slashes and backwards slashes
The best solution might be to roll your own algorithm. Step through the string character by character looking for a slash, and if it finds one, check the next character and previous, if 1 of those exist, then do not insert a duplicate slash because that means it is not alone
This replaces all of the individual occurrences of a character and also fills up an odd number of occurrences:
public static string ReplaceSingle(this string s, char needle)
{
var valueSpan = s.AsSpan();
var length = valueSpan.Length * 2;
char[]? resultArray = null;
Span<char> resultSpan = length <= 256
? stackalloc char[length]
: (resultArray = ArrayPool<char>.Shared.Rent(length));
var value = char.MinValue;
var written = 0;
for (int index = 0; index < valueSpan.Length; index++)
{
value = valueSpan[index];
resultSpan[written++] = value;
if (value == needle && ++index < valueSpan.Length)
{
value = valueSpan[index];
resultSpan[written++] = value == needle ? value : needle;
}
}
var result = new string(resultSpan[..written]);
resultSpan.Clear();
if (resultArray is not null) ArrayPool<char>.Shared.Return(resultArray);
return result;
}
For instance, if you have / it will turn to //, but // will remain. However /// will turn to //// and so on.
There is also a usage of ArrayPool and stackalloc which are aimed at better performance.
Usage:
string value = "This/ is a //Test ///!";
string result = value.ReplaceSingle('/');

How to remove multiple first characters using regex?

I have string string A = "... :-ggw..-:p";
using regex: string B = Regex.Replace(A, #"^\.+|:|-|", "").Trim();
My Output isggw..p.
What I want is ggw..-:p.
Thanks
You may use a character class with your symbols and whitespace shorthand character class:
string B = Regex.Replace(A, #"^[.:\s-]+", "");
See the regex demo
Details
^ - start of string
[.:\s-]+ - one or more characters defined in the character class.
Note that there is no need escaping . inside [...]. The - does not have to be escaped since it is at the end of the character class.
A regex isn't necessary if you only want to trim specific characters from the start of a string. System.String.TrimStart() will do the job:
var source = "... :-ggw..-:p";
var charsToTrim = " .:-".ToCharArray();
var result = source.TrimStart(charsToTrim);
Console.WriteLine(result);
// Result is 'ggw..-:p'

c# How do trim all non numeric character in a string

what is the faster way to trim all alphabet in a string that have alphabet prefix.
For example, input sting "ABC12345" , and i wish to havee 12345 as output only.
Thanks.
Please use "char.IsDigit", try this:
static void Main(string[] args)
{
var input = "ABC12345";
var numeric = new String(input.Where(char.IsDigit).ToArray());
Console.Read();
}
You can use Regular Expressions to trim an alphabetic prefix
var input = "ABC123";
var trimmed = Regex.Replace(input, #"^[A-Za-z]+", "");
// trimmed = "123"
The regular expression (second parameter) ^[A-Za-z]+ of the replace method does most of the work, it defines what you want to be replaced using the following rules:
The ^ character ensures a match only exists at the start of a string
The [A-Za-z] will match any uppercase or lowercase letters
The + means the upper or lowercase letters will be matched as many times in a row as possible
As this is the Replace method, the third parameter then replaces any matches with an empty string.
The other answers seem to answer what is the slowest way .. so if you really need the fastest way, then you can find the index of the first digit and get the substring:
string input = "ABC12345";
int i = 0;
while ( input[i] < '0' || input[i] > '9' ) i++;
string output = input.Substring(i);
The shortest way to get the value would probably be the VB Val method:
double value = Microsoft.VisualBasic.Conversion.Val("ABC12345"); // 12345.0
You would have to regular expression. It seems you are looking for only digits and not letters.
Sample:
string result =
System.Text.RegularExpressions.Regex.Replace("Your input string", #"\D+", string.Empty);

Replace a part of string containing Password

Slightly similar to this question, I want to replace argv contents:
string argv = "-help=none\n-URL=(default)\n-password=look\n-uname=Khanna\n-p=100";
to this:
"-help=none\n-URL=(default)\n-password=********\n-uname=Khanna\n-p=100"
I have tried very basic string find and search operations (using IndexOf, SubString etc.). I am looking for more elegant solution so as to replace this part of string:
-password=AnyPassword
to:
-password=*******
And keep other part of string intact. I am looking if String.Replace or Regex replace may help.
What I've tried (not much of error-checks):
var pwd_index = argv.IndexOf("--password=");
string converted;
if (pwd_index >= 0)
{
var leftPart = argv.Substring(0, pwd_index);
var pwdStr = argv.Substring(pwd_index);
var rightPart = pwdStr.Substring(pwdStr.IndexOf("\n") + 1);
converted = leftPart + "--password=********\n" + rightPart;
}
else
converted = argv;
Console.WriteLine(converted);
Solution
Similar to Rubens Farias' solution but a little bit more elegant:
string argv = "-help=none\n-URL=(default)\n-password=\n-uname=Khanna\n-p=100";
string result = Regex.Replace(argv, #"(password=)[^\n]*", "$1********");
It matches password= literally, stores it in capture group $1 and the keeps matching until a \n is reached.
This yields a constant number of *'s, though. But telling how much characters a password has, might already convey too much information to hackers, anyway.
Working example: https://dotnetfiddle.net/xOFCyG
Regular expression breakdown
( // Store the following match in capture group $1.
password= // Match "password=" literally.
)
[ // Match one from a set of characters.
^ // Negate a set of characters (i.e., match anything not
// contained in the following set).
\n // The character set: consists only of the new line character.
]
* // Match the previously matched character 0 to n times.
This code replaces the password value by several "*" characters:
string argv = "-help=none\n-URL=(default)\n-password=look\n-uname=Khanna\n-p=100";
string result = Regex.Replace(argv, #"(password=)([\s\S]*?\n)",
match => match.Groups[1].Value + new String('*', match.Groups[2].Value.Length - 1) + "\n");
You can also remove the new String() part and replace it by a string constant

how to remove dash(-) in string using c#?

Regex rgx2 = new Regex("[^[0-9] . \n\r\t]");
string dash = Regex.Replace(Des_AccNo.ToString(), #" ^-");
I need to clean this string 100-0#/2^2341?! as 100022341
I don't know what is your code, but you can do that by:
val = val.Replace("-", string.Empty)
If you want to remove all non-numeric characters:
string result = Regex.Replace(inputString, #"[^0-9]", "");
Basically what that says is "if the character isn't a digit, then replace it with the empty string." The ^ as the first character in the character group negates it. That is, [0-9] matches any digit. [^0-9] matches everything except a digit. See Character Classes in the MSDN documentation.
The expression #"[^\d]" also would work
I would basically create a static class that automatically pops up against any string.
If the same is GUID, you can simply do
Guid.NewGuid().ToString("N") returns only characters
Input: 12345678-1234-1234-1234-123456789abc
Output: 12345678123412341234123456789abc
public static string ToNonDashed(this string input)
{
return input?.Replace("-", string.Empty);
}
You can try this:
Des_AccNo = Des_AccNo.Replace("-", string.Empty);
string dash = Des_AccNo.ToString().Replace("-", string.Empty);

Categories