REGEX help for replacing a value - c#

I have below Json which is having -INF in its value and I need to replace INF with "Infinity". Below is the sample JSON and REGEX which does the trick for me. I am looking for ways I can optimize the below method and if I can use a single Regex instead of two.
Sample Json : "Power_dB":[-INF,-1000,-1000,-1000,-INF,-INF,-INF,-INF]
My code:
var pattern = #"-(INF){1},";
var secondPattern = #"-(INF){1}\]";
string replacement = "-Infinity,";
string secondreplacement = "-Infinity]";
string result = Regex.Replace( json, pattern, replacement );
result = Regex.Replace( result, secondPattern, secondreplacement );
var settings = new JsonSerializerSettings() { FloatFormatHandling = FloatFormatHandling.Symbol };
var data = JsonConvert.DeserializeObject<JObject>( result, settings ) ;
Above code gives me desired output as below:
"Power_dB":["-INFINITY",-1000,-1000,-1000,"-INFINITY","-INFINITY","-INFINITY","-INFINITY"]

I would suggest changing your expression to this:
-INF(?=[,\]])
Breaking it down:
-INF - Match the literal "-INF"
(?=something) - Positive lookahead. The expression only matches if this also matches, but this doesn't capture.
[,\]] - Match , or ]. In this case we have no modifier after it so it will only match a single character.
Then you can simply replace the matched part with this:
-Infinity
C# code:
var regex = new Regex(#"-INF(?=[,\]])");
string input = "\"Power_dB\":[-INF,-1000,-1000,-1000,-INF,-INF,-INF,-INF]";
string result = regex.Replace(input, "-Infinity");
Console.WriteLine(result);
Try it online

Related

Matching a result in c#

I have the following string
background-image: url('https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg')
and I just want to get the image URL.
My code is:
image = image.Replace(#"'", "\"");
Match match = Regex.Match(image, #"'([^']*)");
Match.Success returns nothing, so I can not get the image URL.
Is there something missing? This used to work but not now.
The following pattern achieves your result, without the usage of string.replace.
var pattern = #"'(?<url>.*)'";
Match match = Regex.Match(image, pattern);
Console.WriteLine($"Math: {match.Groups["url"].Value}");
If you want the " surrounding the string, add this:
var result = $"\"{match.Groups["url"].Value}\""
No need for a regex, just
Split the string with ' substring
Find the element starting with http
Return the first found item.
C# demo:
var s = "background-image: url('https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg')";
var res = s.Split(new[] {"'"}, StringSplitOptions.None)
.Where(v => v.StartsWith("http"))
.FirstOrDefault();
Console.WriteLine(res);
// => https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg
If you need to use a regex, use the standard regex to match a string between two strings, start(.*?)end where (.*?) captures into Group 1 any 0 or more chars other than a newline, as few as possible as the *? quantifier is lazy:
var s = "background-image: url('https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg')";
var res = Regex.Match(s, #"'(.*?)'").Groups[1].Value ?? string.Empty;
Console.WriteLine(res);
// => https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg
See another C# demo
The regex of: (\".*\")
Will match the URL given the input string:
background-image: url("https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg")
image = image.Replace(#"'", "\"");
Match match = Regex.Match(image, "(\\\".*\\\")");
Edit:
If you are looking for something that will match pairs of single quotes or double quotes you could use:
(\".*\"|'.*')
Match match = Regex.Match(image, "(\\\".*\\\"|'.*')");

start from end of string till special character c#

This is probably a super easy question but I can't seem to figure it out. Do you know how to extract just the portion after the '/' in a string. So for like the following:
[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]
So I just want the 'OrderConfirmation_SynergyWorldInc' portion. I got 271 entries where I gotta extract just the end portion (the all have the portions before that in all of them, if that helps).
Thanks!!
IF YOU HAVE A SINGLE ENTRY...
You need to use LastIndexOf with Substring after a bit of trimming:
var s = #"[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]";
s = s.Trim('[',']');
Console.Write(s.Substring(s.LastIndexOf('\\') + 1));
Result: OrderConfirmation_SynergyWorldInc
IF YOU HAVE MULTIPLE RECORDS...
You can use a regex to extract multiple matches from a large text containing [...] substring:
[^\\\[\]]+(?=\])
See demo
For [HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc][SOMEENTRY] string, you will then get 2 results:
The regex matches
[^\\\[\]]+ - 1 or more characters other than ], [ and \
(?=\]) - before the end ] character.
C#:
var results = Regex.Matches(s, #"[^\\\[\]]+(?=\])").OfType<Match>().Select(p => p.Value).ToList();
var s = #"[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]";
Console.WriteLine (s.Trim(']').Split('\\').Last());
prints
OrderConfirmation_SynergyWorldInc
var key = #"[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]";
key = key.Replace("[", string.Empty);
key = key.Replace("]", string.Empty);
var splitkeys =key.Split('\\');
if (splitkeys.Any())
{
string result = splitkeys.Last();
}
Try:
string orderConfirmation = yourString.Split(new []{'\\\'}).Last();
You may also want to remove the last character if the brackets are included in the string.
string pattern = ".*\\(\w*)";
string value = "[HKEY_LOCAL_MACHINE\SOFTWARE\4YourSoul\Server\ReportEMailService\OrderConfirmation_SynergyWorldInc]"
Regex r = new Regex(pattern);
Match m = r.Match(value);

Would like to split a string using a regex pattern

I have a string that I would like to split into
var finalQuote = "2012-0001-1";
var quoteNum = "2012-0001";
var revision = "1"
I used something like this
var quoteNum = quoteNum.subString(0,9);
var revision = quoteNum.subString(quoteNum.lastIndexOf("-") + 1);
But can't it be done using regex more efficiently? I come across patterns like this that need to be split into two.
var finalQuote = "2012-0001-1";
string pat = #"(\d|[A-Z]){4}-\d{4}";
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(text);
var quoteNum = m.Value;
So far I have reached here. But I feel I am not using the correct method. Please guide me.
EDIT: I wanna edit by the pattern. Splitting with dashes is not an option as the first part of the split contains a dash. ie, "2012-0001"
I would simply go with:
var quoteNum = finalQuote.Substring(0,9);
var revision = finalQuote.Substring(10);
quoteNum would consist of the first 9 characters, and revision of the 10th and everything that may follow the 10th, e.g. if the revision is 10 or higher it would still work.
Using complicated regexes or extension methods is very quickly overkill; sometimes the simple methods are efficient enough by itself.
I would agree with others that using substring is a better solution than regex for this.
But if you're insisting on using regex you can use something like:
^(\d{4}-\d{4})-(\d)$
Untested since I don't have a C# environment installed:
var finalQuote = "2012-0001-1";
string pat = #"^(\d{4}-\d{4})-(\d)$";
Regex r = new Regex(pat);
Match m = r.Match(finalQuote);
var quoteNum = m.Groups[1].Value;
var revision = m.Groups[2].Value;
Alternatively, if you want a string[] you could try (again, untested):
string[] data = Regex.Split("2012-0001-1",#"-(?=\d$)");
data[0] would be quoteNum and data[1] would be revision.
Update:
Explanation of the Regex.Split:
From the Regex.Split documentation: The Regex.Split methods are similar to the String.Split method, except that Regex.Split splits the string at a delimiter determined by a regular expression instead of a set of characters.
The regex -(?=\d$) matches a single - given it is followed by a digit followed by the end of the string so it would only match the last dash in the string. The last digit is not consumed because we use a zero-width lookahead assertion (?=)
sIt would be easier to maintain in the future if you something that the new comer would understand.
you could use:
var finalQuote = "2012-0001-1";
string[] parts = finalQuote.Split("-");
var quoteNum = parts[0] + "-" + parts[1] ;
var revision = parts[3];
However if you insists you need a regEx then
(\d{4}-\d{4})-(\d)
There are two groups in this expression, group 1 capture the first part and the group 2 capture the second part.
var finalQuote = "2012-0001-1";
string pat = #"(\d{4}-\d{4})-(\d)";
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(finalQuote);
var quoteNum = m.Groups[1].Value;
var revision = m.Groups[2].Value;

Regex to match pattern in C#

I have a string in the following format
ABC=23:Qasd=56:Def=40.44
I would like to replace all the strings (ABC=, Qasd= and Def=) with empty string. The string after = can be anything. So my output string would be
23:56:40.44
It would be great if you can let me know the regex for that in C#
(^|:)[^=]*=
replaced with
$1
Matches the beginning of a string or a : and everything until and including =.
It is replaced with $1 to keep :.
C#
string strTargetString = #"ABC=23:Qasd=56:Def=40.44";
var myRegex = new Regex(#"(^|:)[^=]*=");
var result = myRegex.Replace(strTargetString, #"$1");
//result: 23:56:40.44
More examples:
ABC=hello:Qasd=56:Def=40.44 => hello:56:40.44
Match
^[^=]+=|(?<=:)[^=]+=
and replace with string.Empty
Regex.Replace("ABC=23:Qasd=56:Def=40.44", #"^[^=]+=|(?<=:)[^=]+=", string.Empty);

C# regular expression to find custom markers and take content

I have a string:
productDescription
In it are some custom tags such as:
[MM][/MM]
For example the string might read:
This product is [MM]1000[/MM] long
Using a regular expression how can I find those MM tags, take the content of them and replace everything with another string? So for example the output should be:
This product is 10 cm long
I think you'll need to pass a delegate to the regex for that.
Regex theRegex = new Regex(#"\[MM\](\d+)\[/MM\]");
text = theRegex.Replace(text, delegate(Match thisMatch)
{
int mmLength = Convert.ToInt32(thisMatch.Groups[1].Value);
int cmLength = mmLength / 10;
return cmLength.ToString() + "cm";
});
Using RegexDesigner.NET:
using System.Text.RegularExpressions;
// Regex Replace code for C#
void ReplaceRegex()
{
// Regex search and replace
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(#"\[MM\](?<value>.*)\[\/MM\]", options);
string input = #"[MM]1000[/MM]";
string replacement = #"10 cm";
string result = regex.Replace(input, replacement);
// TODO: Do something with result
System.Windows.Forms.MessageBox.Show(result, "Replace");
}
Or if you want the orginal text back in the replacement:
Regex regex = new Regex(#"\[MM\](?<theText>.*)\[\/MM\]", options);
string replacement = #"${theText} cm";
A regex like this
\[(\w+)\](\d+)\[\/\w+\]
will find and collect the units (like MM) and the values (like 1000). That would at least allow you to use the pairs of parts intelligently to do the conversion. You could then put the replacement string together, and do a straightforward string replacement, because you know the exact string you're replacing.
I don't think you can do a simple RegEx.Replace, because you don't know the replacement string at the point you do the search.
Regex rex = new Regex(#"\[MM\]([0-9]+)\[\/MM\]");
string s = "This product is [MM]1000[/MM] long";
MatchCollection mc = rex.Matches(s);
Will match only integers.
mc[n].Groups[1].Value;
will then give the numeric part of nth match.

Categories