This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there an alternative to string.Replace that is case-insensitive?
I'm looking for alternative to:
string str = "data ... ";
string replace = "data";
str = str.Replace(replace, "new value");
str = str.Replace(replace.ToLower(),"new value");
if possible using no regex.
Thanks in advance.
Without Regex, I don't know.
With Regex, it would give you something like this :
var regex = new Regex( str, RegexOptions.IgnoreCase );
var newSentence = regex.Replace( sentence, "new value" );
I found an interesting article here, with a sample code that looks to work faster than Regex.Replace : http://www.codeproject.com/KB/string/fastestcscaseinsstringrep.aspx
Related
This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 2 years ago.
I have a couple of strings and I want them to be transformed like shown below
In the first two examples " is included in the input string.
But " does not comes always with the input string as shown in last two examples.
Basically I need the string between |" and "| or string between first and last occurrence of |
Can someone please let me know how to find the match for the output string that I need which will work for all of these strings? I am trying to code these in C#.
Thanks in advance for any help
I would propose an alternative to regex. Simply using Substring and Replace:
List<string> input = new List<string>
{
"501000061|\"B084PD449Q|2088|1\"|",
"504000585|\"B000NSIAG0|3115|0\"|",
"508000036|B084S1FVH5|42|1|",
"504000584|B000NSIAG0|3115|0|"
};
foreach (var element in input)
{
string transformed = element.Substring(10, element.Length - 11)
.Replace("\"", string.Empty);
Console.WriteLine(transformed);
}
Output:
B084PD449Q|2088|1
B000NSIAG0|3115|0
B084S1FVH5|42|1
B000NSIAG0|3115|0
^[0-9]{9}\|"?([A-Z0-9]){10}\|([0-9]){2,}\|([0-9])"?\|$
This regex is a bit more rigid than the ones already proposed based on the input examples that you've provided.
I suggest you look into non-regex solutions that have already been pointed out, however, if you absolutely must use regex here's how to do it in C# for this example.
var pattern = #"^[0-9]{9}\|"?([A-Z0-9]){10}\|([0-9]){2,}\|([0-9])"?\|$";
var replacement = "$1|$2|$3";
var input = "501000061|\"B084PD449Q|2088|1\"|";
var result = Regex.Replace(input, pattern, replacement);
Here's one without regex:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var inp = "504000585|\"B000NSIAG0|3115|0\"|";
var res = string
.Join("|", inp.Split(new []{'|'}, StringSplitOptions.RemoveEmptyEntries).Skip(1))
.Replace("\"", "");
Console.WriteLine(res);
}
}
https://dotnetfiddle.net/i39XUY
B000NSIAG0|3115|0
This question already has answers here:
How to replace the text between two characters in c#
(7 answers)
Closed 5 years ago.
I was wondering how do I use regex to replace string between two characters.
var oldString = "http://localhost:61310/StringtoConvert?Id=1"
Expected result = "http://localhost:61310/ConvertedString?Id=1"
No need for regex or string operations, use UriBuilder class.
var oldString = "http://localhost:61310/StringtoConvert?Id=1";
var newuri = new UriBuilder(new Uri(oldString));
newuri.Path = "ConvertedString";
var result = newuri.ToString();
You can use Regex.Replace(string, string, string). So, if you want to replace a substring between a / and a ?, you can use
string result = Regex.Replace(oldString, "(?<=\/)[^\?]*(?=\?)", "ConvertedString");
?<= is a lookbehind, \/ escapes the slash character, [^\?]* matches any characters not a ? any number of times, ?= is a lookahead, and \? escapes the question mark character.
Instead of Regex, you can use the System.Uri class then concatenate or interpolate your new value:
private static string ReplacePath(string url, string newPath)
{
Uri uri = new Uri(url);
return $"{uri.GetLeftPart(UriPartial.Authority)}/{newPath}{uri.Query}";
}
Calling this method with your url, and the new path (ie "ConvertedString") will result in the output: "http://localhost:61310/ConvertedString?Id=1"
Fiddle here.
EDIT
#Eser's answer is way better than mine. Did not know that class existed. Mark their answer as the right one not mine.
This question already has answers here:
Escape Special Character in Regex
(3 answers)
Closed 5 years ago.
I am trying to use RegEx to replace a string, but nothing is being replaced. I'm not sure what I'm doing wrong.
System.Text.RegularExpressions.Regex regEx = null;
regEx = new System.Text.RegularExpressions.Regex("DefaultStyle.css?x=839ua9");
pageContent = regEx.Replace(htmlPageContent, "DefaultStyleSnap.css?x=742zh2");
htmlPageContent is of type string, and contains the html page content of the Render method (write before we send it to the browser). The htmlPageContent string definitely contains "DefaultStyle.css?x=839ua9". I can see it when I do Quick Watch in visual studio, and when I view Page Source.
Why is RegEx not replacing the string?
You have to use \? and \. instead of ? and . in your Regex. Please check below code.
CODE:
using System;
public class Program
{
public static void Main()
{
string htmlPageContent = "Some HTML <br> DefaultStyle.css?x=839ua9";
string pageContent = "";
System.Text.RegularExpressions.Regex regEx = null;
//regEx = new System.Text.RegularExpressions.Regex("DefaultStyle.css?x=839ua9");
regEx = new System.Text.RegularExpressions.Regex(#"DefaultStyle\.css\?x=839ua9");
pageContent = regEx.Replace(htmlPageContent, "DefaultStyleSnap.css?x=742zh2");
Console.WriteLine(pageContent);
}
}
Output:
Some HTML <br> DefaultStyleSnap.css?x=742zh2
You can check the output in DotNetFiddle.
You need to escape your special characters using \.
System.Text.RegularExpressions.Regex regEx = null;
regEx = new System.Text.RegularExpressions.Regex("DefaultStyle\.css\?x=839ua9");
pageContent = regEx.Replace(htmlPageContent, "DefaultStyleSnap.css?x=742zh2");
You need to explicitly escape the ? which means 0 or more of the previous character.
As for the . if you do not escape it, you will match any characters. It would be more precise to escape it as well to make sure you don't match something like
DefaultStyle-css?x=839ua9
This question already has answers here:
How to remove the exact occurence of characters from a string?
(7 answers)
Closed 6 years ago.
i have a string like string st ="12,34,56,345,12,45" and i want remove number 34 from this string i did like string newst = st.replace(",34",""); but it is removing 34 from 345 , how to prevent this
EDIT
34 can be anywhere,here i am generating dynamically
It's very simple:
var st ="12,34,56,345,12,45";
var newst = st.replace(",34,", ",");
If it can be anywhere, you may use the regular expression:
var input = "34,234,35,36,34,37,345,34";
var pattern = #",?\b34\b,?";
var regex = new Regex(pattern);
var result = regex.Replace(input, ",").Trim(',');
Shorter notation could look like this:
var result = Regex.Replace(input, #",?\b34\b,?", ",").Trim(',');
Explanation of the regular expression: ,?\b34\b,? matches the word 34, but only if preceded and followed by word-delimiter characters (because of the word boundary metacharacter \b), and it can be (but doesn't have to be) preceded and followed by the comma thanks to ,? which means none or more comma(s).
At the end we need to remove possible commas from the beginning and end of the string, that's why there's Trim(',') on the result.
But I would say #crashmstr's solution is better than trying to tune the regular expression for this particular use case.
This will work:
var oldString = "34,12,34,56,345,12,45,34";
var newString = String.Join(",", oldString.Split(',').Where(x => x != "34"));
We split on ',', use LINQ to exclude "34", then join the string back together by ','.
Try this
string newst = st.replace(",34,",",");
Granted this only works if the number you want to replace is between two commas. If you want something more advanced, use Regex.Replace()
Here's an example:
string temp = Regex.Replace("12,34,56,345,12,45", #"^34,", "");
string newst = Regex.Replace(temp, #"34$,", "");
You could also use String.TrimStart and .TrimEnd to clean up the borders.
Also, I like crashmstr's example.
split and work in list:
string[] arr = st.Split(',');
List<string> list = arr.ToList();
list.Remove("34");
or regex:
var replaced = Regex.Replace(st, #"\b34\b[,]","");
This question already has answers here:
return only Digits 0-9 from a String
(8 answers)
Closed 3 years ago.
Is there any better way to get take a string such as "(123) 455-2344" and get "1234552344" from it than doing this:
var matches = Regex.Matches(input, #"[0-9]+", RegexOptions.Compiled);
return String.Join(string.Empty, matches.Cast<Match>()
.Select(x => x.Value).ToArray());
Perhaps a regex pattern that can do it in a single match? I couldn't seem to create one to achieve that though.
Do you need to use a Regex?
return new String(input.Where(Char.IsDigit).ToArray());
Have you got something against Replace?
return Regex.Replace(input, #"[^0-9]+", "");
You'll want to replace /\D/ (non-digit) with '' (empty string)
Regex r = new Regex(#"\D");
string s = Regex.Replace("(123) 455-2344", r, "");
Or more succinctly:
string s = Regex.Replace("(123) 455-2344", #"\D",""); //return only numbers from string
Just remove all non-digits:
var result = Regex.Replace(input, #"\D", "");
In perl (you can adapt this to C#) simply do
$str =~ s/[^0-9]//g;
I am assuming that your string is in $str. Basic idea is to replace all non digits with '' (i.e. empty string)