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.
Related
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[,]","");
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I need a c# regular expression for extracting the prefix of a string which has a postfix of 2 characters and a number.
I MUST USE REGEX
example:
input: "ABCDZZ4321"
output: "ABCD"
I want to cut the two 'Z' characters and the number at the end.
Another example:
input: "ABCD4R4321"
output: "ABCD"
Why bother with Regex:
var result = "ABCDZZ4321".Split('Z')[0];
EDIT:
Regex version.. even though its highly overkill:
var match = Regex.Match("ABCDZZ4321", #"^(\w+?)([A-Z0-9]{2})(\d+)$");
var result = match.Groups[1].Value; // 1 is the group.. 0 is the whole thing.
Regex is fixed now. As far as I can tell.. this will work for your requirements.
Perhaps something like this would do?
^(\w+?)\w{2}\d+$
In-depth explanation:
^ = match the beginning of the string.
\w = match any non-whitespace character(s)
\w+ = match one or more of these
\w+? = match one or more, in a "non-greedy" way (i.e. let the following match take as much as possible, which is important in this case)
\w{2} = match two non-whitespace characters
\d+ = match one or more digit character
$ = match the end of the string
(I used this site to test the regexp out while writing it.)
Also, if you only need to match A-Z, you can replace \w with [A-Z]; it seems more appropriate in that case.
You can also use this regex: (.*?ZZ) and then remove ZZ or replace whit ""
You could use ^\w{3,}\d+$. This would locate any strings that begin with at least 3 chars (2 that you need in the middle and 1 so that you have something to return) and that ends with some set of digits.
Another way is to use the string.LastIndexOf()
string input = "ABCDZZ4321";
string splitOn = "ZZ";
string result = input.Substring(0, input.LastIndexOf(splitOn));
Please try following code. I have tried with "ABCDZZ4321" and long input string in below code. In both tests it's giving required result "ABCD".
string input = "ABCDZZ455555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555321";
Regex rgx = new Regex("(?<content>.*?)[a-zA-Z]{2}[0-9]+");
Match MatchResult = rgx.Match(input);
string result = string.Empty;
while (MatchResult.Success)
{
result = MatchResult.Groups["content"].Value;
break;
}
Then even like this.
var input = "ABCDZZ4321";
var zzIndex = input.IndexOf("ZZ");
var output = input.Substring(0, zzIndex);
Regex is definitely an overengineering here
Regex.Replace(input, #"^(.+)ZZ\d+$", "$1")
Explanation:
all what comes at start of string will be catched in the group 1 (round parenthesis). In the replacement patterns it will be referenced with '$1'.
Greet you OP from the community ;)
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do I extract PART of a specific string from a huge chunk of ugly strings?
String:
https://company.zendesk.com/api/v2/tickets/33126.json
I need the number 33126.
What's the optimal way to extract this number?
Since that is a path/url, use Path.GetFileNameWithoutExtension:
string name = Path.GetFileNameWithoutExtension(path);
I would prefer Path, but if you want to use the Uri class instead, you can also use this:
Uri uri = new Uri("https://company.zendesk.com/api/v2/tickets/33126.json");
string lastSegment = uri.Segments.Last();
string name = lastSegment.Substring(0, lastSegment.IndexOf('.'));
This looks like a job for regular expressions.
Regex regex = new Regex(#"https://company.zendesk.com/api/v2/tickets/(\d+).json");
Match match = regex.Match("https://company.zendesk.com/api/v2/tickets/33126.json");
foreach(Group group in match.Groups)
{
Console.WriteLine(group.Value);
}
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)