RegEx in C# Replace Method [duplicate] - c#

This question already has answers here:
C#: How to Delete the matching substring between 2 strings?
(6 answers)
Closed 4 years ago.
I am trying to write the RegEx for replacing "name" part in below string.
\profile\name\details
Where name: -Can have special characters
-No spaces
Let's say I want to replace "name" in above path with ABCD, the result would be
\profile\ABCD\details
What would be the RegEx to be used in Replace for this?
I have tried [a-zA-Z0-9##$%&*+\-_(),+':;?.,!\[\]\s\\/]+$ but it's not working.

As your dynamic part is surrounded by two static part you can use them to find it.
\\profile\\(.*)\\details
Now if you want to replace only the middle part you can either use LookAround.
string pattern = #"(?<=\\profile\\).*(?=\\details)";
string substitution = #"titi";
string input = #"\profile\name\details
\profile\name\details
";
RegexOptions options = RegexOptions.Multiline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
Or use the replacement patterns $GroupIndex
string pattern = #"(\\profile\\)(.*)(\\details)";
string substitution = #"$1Replacement$3";
string input = #"\profile\name\details
\profile\name\details
";
RegexOptions options = RegexOptions.Multiline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
For readable nammed group substitution is a possibility.

Related

Regex.Matches doesn't find match [duplicate]

This question already has answers here:
Why \b does not match word using .net regex
(2 answers)
Closed 3 years ago.
I'm using Visual C# to create a little tool to support some people doing simple text manipulations. The tool has a GUI but uses regex in the code. Most things work already but now I found a problem that I'm not able to solve. I want to find the string MY2020 at the start of a word. Here's my code:
string TestString = "we have the string MY2020 somewhere in the line";
string Pattern = "\bMy2020";
RegexOptions options = RegexOptions.IgnoreCase;
MatchCollection myMatches = Regex.Matches(TestString, Pattern, options);
if (myMatches.Count > 0)
{
I expect MY2020 to be found. So myMatches.Count should be 1, but it's 0.
In parallel I use an online regex tester (https://regex101.com/). This one shows a match.
What am I missing?
You need to escape the "\", I have modified your code as
string TestString = "we have the string MY2020 somewhere in the line";
string Pattern = #"\bMy2020";
RegexOptions options = RegexOptions.IgnoreCase;
MatchCollection myMatches = Regex.Matches(TestString, Pattern, options);
if (myMatches.Count > 0)

Split a string after reading square brackets in c# [duplicate]

This question already has answers here:
splitting a string based on multiple char delimiters
(7 answers)
Closed 5 years ago.
string test = "Account.Parameters[\"AccountNumber\"].Caption";
string new = test.Trim("[");
I want output "AccoutNumber".
I have tried the below code but not getting the desired result:
string[] test = "Transaction.Parameters[\"ExpOtherX\"].Caption".Split('[');
string newvalue = test[1];
Just use Split with two delimiters:
string[] test = "Transaction.Parameters[\"ExpOtherX\"].Caption".Split('[', ']');
string newvalue = test[1];
You can also use Regex:
string test = "Account.Parameters[\"AccountNumber\"].Caption";
var match = System.Text.RegularExpressions.Regex.Match(test, ".*?\\.Parameters\\[\"(.*?)\"]");
if (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
}
.*? is a non greedy wildcart capture, so it will match your string until it reaches the next part (in our case, it will stop at .Parameters[", match the string, and then at "])
It will match .Parameters["..."]., and extract the "..." part.
you can do a Split to that string...
string test = "Account.Parameters[\"AccountNumber\"].Caption";
string output = test.Split('[', ']')[1];
Console.WriteLine(output);

Replace part of RegEx pattern in C#

The code below works
string pattern = "\"cs\":\".*?\"";
string replacement = "\"cs\":\"\"";
Regex rgx = new Regex(pattern);
string stripped = rgx.Replace(resp.JsonResponse, replacement);
But is it possible to tweak this so that I only replace .*? with nothing.
string pattern = "(exclude:\"cs\":\").*?(exclude:\")";
string replacement = "";
Regex rgx = new Regex(pattern);
string stripped = rgx.Replace(resp.JsonResponse, replacement);
Yes, by only matching .*? and adding positive lookahead/lookbehind assertions to ensure it only matches when the conditions are correct.
So, change your pattern to
(?<="cs":").*?(?=")
(unescaped)
Now, you'll only match .*? when it is preceded by "cs":" and followed by ".
Q: It looks like you're editing JSON. Is there a reason that you don't want to defer this work to a JSON parser?

Escaping characters in RegEx pattern string [duplicate]

This question already has answers here:
Escape Special Character in Regex
(3 answers)
Closed 7 years ago.
I'm trying to extract MTQ0ODQ3NjcyNDoxNDQ4NDc2NzI0OjE6LTM4OTc1OTc2MjM4MDc1OTM2NjY6MTQ0ODQ3NjAwMzowOjA6NTQw from the string below.
I am having issues with the \\ (backslash) characters. How do I escape these in C#. Is there any documentation that shows characters that need escaping in regex patterns, and how to escape them?
first_cursor\\":\\"MTQ0ODQ3NjcyNDoxNDQ4NDc2NzI0OjE6LTM4OTc1OTc2MjM4MDc1OTM2NjY6MTQ0ODQ3NjAwMzowOjA6NTQw\\"
I've tried the following to no avail. I tried to avoid having to escape the backslashes altogether:
MatchCollection matches = Regex.Matches(content, "first_cursor*.quot;([-0-9A-Za-z]+)");
Any help would be much appreciated.
In C# each backslash in a string can be written as \\\\.
You can use the following:
MatchCollection matches = Regex.Matches(content, "first_cursor\\\\{2}":\\\\{2}&quot([-0-9A-Za-z]+)");
I prefer to use verbatim string literals when writing RegEx strings in C#:
string pattern = #"first_cursor\\\\":\\\\"([-0-9A-Za-z]+)\\\\"";
This prevents you from having to escape the slashes twice; once for C# and again for the RegEx engine.
As an aside, this syntax is also useful when storing paths in strings:
string logFile = #"C:\Temp\mylog.txt";
And even supports multi-line for SQL commands and such:
string query = #"
SELECT *
FROM tblStudents
WHERE FirstName = 'Bobby'
AND LastName = 'Tables'
";
You can use lookahead to elimate some of the contenders:
var example = #"first_cursor\\":\\"MTQ0ODQ3NjcyNDoxNDQ4NDc2NzI0OjE6LTM4OTc1OTc2MjM4MDc1OTM2NjY6MTQ0ODQ3NjAwMzowOjA6NTQw\\"";
var regex = new Regex("(?<!&[-0-9A-Za-z]*)(?<!_[-0-9A-Za-z]*)[-0-9A-Za-z]+");
var matches = regex.Matches(example);
foreach(var match in matches)
{
if (match.ToString() != "first")
{
Console.WriteLine(match);
}
}
This would give you two matches. One for first and one for the string you are looking for. Then you can iterate over the matches and see if it's not "first" then it should be what you are looking for.

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);

Categories