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'
Related
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
So, I'm trying to remove certain characters [.&#] before the final occurance of an #, but after that final #, those characters should be allowed.
This is what I have so far.
string pattern = #"\.|\&|\#(?![^#]+$)|[^a-zA-Z#]";
string input = "username#middle&something.else#company.com";
// input, pattern, replacement
string result = Regex.Replace(input, pattern, string.Empty);
Console.WriteLine(result);
Output: usernamemiddlesomethingelse#companycom
This currently removes all occurances of the specified characters, apart from the final #. I'm not sure how to get this to work, help please?
You may use
[.&#]+(?=.*#)
Or, equivalent [.&#]+(?![^#]*$). See the regex demo.
Details
[.&#]+ - 1 or more ., & or # chars
(?=.*#) - followed with any 0+ chars (other than LF) as many as possible and then a #.
See the C# demo:
string pattern = #"[.&#]+(?=.*#)";
string input = "username#middle&something.else#company.com";
string result = Regex.Replace(input, pattern, string.Empty);
Console.WriteLine(result);
// => usernamemiddlesomethingelse#company.com
Just a simple solution (and alternative to complex regex) using Substring and LastIndexOf:
string pattern = #"[.#&]";
string input = "username#middle&something.else#company.com";
string inputBeforeLastAt = input.Substring(0, input.LastIndexOf('#'));
// input, pattern, replacement
string result = Regex.Replace(inputBeforeLastAt, pattern, string.Empty) + input.Substring(input.LastIndexOf('#'));
Console.WriteLine(result);
Try it with this fiddle.
How can I append a known string before each coma on a comma separated string.
Is there a regex for that or something that doesn't use a loop
EX
given string :
email, email2, email3 (etc...)
to
string suffix = "#iou.com"
string desiredResult = "email#iou.com, email2#iou.com, email3#iou.com
Thank you!!
You can use [^,\s]+ regexp, and replace with "$0"+suffix:
var res = Regex.Replace(original, #"[^,\s]+", "$0"+suffix);
"$0" refers to the content captured by the regular expression.
Demo.
Or using LINQ:
Console.WriteLine(string.Join(",",input.Split(',').Select(s => string.Concat(s, suffix))));
You could use a zero-length capture group. Here's how that might look:
\w+(?<ReplaceMe>),?
The \w matches alphanumeric characters, and the named capture group called "ReplaceMe" matches the zero-length space between the end of the word and the beginning of the comma (or any other non-alphanumeric item, including the end of the string).
Then you'd just replace ReplaceMe with the appended value, like this:
Regex.Replace(original, #"\w+(?<ReplaceMe>),?", "#email.com");
Here's an example ofthat regex in action.
Here you are:
string input = "email, email2, email3";
string suffix = "#iou.com";
//string desiredResult = "email#iou.com, email2#iou.com, email3#iou.com";
Console.WriteLine(Regex.Replace((input + ",")
.Replace(",", suffix + ","), #",$", ""));
Hope this helps.
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);
Using C# we can do string check like if string.contains() method, e.g.:
string test = "Microsoft";
if (test.Contains("i"))
test = test.Replace("i","a");
This is fine. But what if I want to replace a string which contains " symbol to be replaced.
I want to achieve this:
"<html><head>
I want to remove the " symbol present in check so that the result would be:
<html><head>
The " character can also be replaced, just like any other:
test = test.Replace("\"","");
Also, note that you don't have to test if the character exists : your test.Contains("i") could be removed since the .Replace() method won't do anything (no replace, no error thrown) if the character doesn't exist inside the string.
To include a quote symbol in a string, you need to escape it, using a backslash. In your example, you want to use something lik this:
if (test.Contains("\""))
There are two ways to include a '"' character in a string literal. All the answers so far have used the c-style way:
var quotation = "Parting is such sweet sorrow";
var howSweetIsIt = quotation + " that I shall say \"good-night\" till it be morrow.";
In some contexts (especially for users experienced with Visual Basic), the verbatim string literal may be easier to read. A verbatim string literal begins with an # sign, and the only character that requires escaping is the quotation mark -- all other characters are included verbatim (hence the name). Significantly, the method of escaping the quotation mark is different: rather than preceding it with a backslash, it must be doubled:
var howSweetIsIt = quotation + " that I shall say ""good-night"" till it be morrow.";
string SymbolString = "Micro\"so\"ft";
The string above use scape char \ to insert " between the characters
string Result = SymbolString.Replace("\"", string.Empty);
With the following replace I replace the character "" for empty.
This is what you try to achieve?
if (check.Contains("\"")
output = check.Replace("\"", "");
output = check.Replace("\"", "");
Just remember to use "\"" for the quote sign as the backslash is an escape character.
if (str.Contains("\""))
{
str = str.Replace("\"", "");
}