replace variable name in formula with Regex.Replace - c#

In c#, I want use a regular expression to replace each variable #A with a number withouth replacing other similar variables like #AB
string input = "3*#A+3*#AB/#A";
string value = "5";
string pattern = "#A"; //<- this doesn't work
string result = Regex.Replace(input, pattern, value);
// espected result = "3*5+3*#AB/5"
any good idea?

Use a word boundary \b:
string pattern = #"#A\b";
See regex demo (Context tab)
Note the # before the string literal: I am using a verbatim string literal to declare the regex pattern so that I do not have to escape the \. Otherwise, it would look like string pattern = "#A\\b";.

Related

Regular Expression for a middle string

I need to extract from the below string
2_240219_0.vnd as 240219
I have tried as follows: _[0-9]+_
This gives me _240219_
How do I remove the _ from both ends.
I would actually recommend not even using regex in this case. A simple string split on underscore should do just fine:
string input = "2_240219_0.vnd";
string middle = input.Split('_')[1];
Console.WriteLine(middle);
240219
You can try using a other regex: ([\d]{6,})
Match m = Regex.Match(2_240219_0.vnd, `([\d]{6,})`, RegexOptions.IgnoreCase);

String pattern delimiter

I have this code:
string first = "2-18;1-4; 5-212; 4-99" ;
Char delimiter = '-';
String pattern = #"\s?(\d+)([-])(\d+)";
And I would like to know if there is any way to put the delimiter in the pattern instead of the ([-]) ?
You could use string interpolation:
string first = "2-18;1-4; 5-212; 4-99" ;
Char delimiter = '-';
String pattern = $#"\s?(\d+)([{delimiter}])(\d+)";
The $ sign (which has to be in front of the #) makes it possible to put a variable (string) in a string by using { }
Note: In older versions of C# however this will not work
In this case you can use string.Format:
string.Format(#"\s?(\d+)([{0}])(\d+)", delimiter);
This works the same way but uses number placeholders for the parameters after the ,
Regex.Escape: (Credits to NtFreX)
Additionally if you are using regex you should escape your character (because they can mean something else in regex).
$#"\s?(\d+)([{Regex.Escape( delimiter.ToString() )}])(\d+)";
This is simplest string concatenation. You have several options:
string concatenation:
Char delimiter = '-';
String pattern = #"\s?(\d+)([" + delimiter + "])(\d+)";
string.Format():
Char delimiter = '-';
String pattern = string.Format(#"\s?(\d+)([{0}])(\d+)", delimiter);
new style Format (only works with newer C# versions):
Char delimiter = '-';
String pattern = $#"\s?(\d+)([{delimiter}])(\d+)";
Additionaly I would use Regex.Escape to escape the delimiter.
$#"\s?(\d+)([{Regex.Escape(delimiter)}])(\d+)";
For example if the delimiter is . it needs to be changed into \. because . is a special regex character which matches any character. The same goas for other characters.

Passing a dynamic value to quantifier in C# regex

I have a regex that I am trying to pass a variable to:
int i = 0;
Match match = Regex.Match(strFile, "(^.{i})|(godness\\w+)(?<=\\2(\\d+).*?\\2)(\\d+)");
I'd like the regex engine to parse {i} as the number that the i variable holds.
The way I am doing that does not work as I get no matches when the text contains matching substrings.
It is not clear what strings you want to match with your regex, but if you need to use a vriable in the pattern, you can easily use string interpolation inside a verbatim string literal. Verbatim string literals are preferred when declaring regex patterns in order to avoid overescaping.
Since string interpolation was introduced in C#6.0 only, you can use string.Format:
string.Format(#"(^.{{{0}}})|(godness\w+)(?<=\2(\d+).*?\2)(\d+)", i)
Else, beginning with C#6.0, this seems a better alternative:
int i = 0;
Match match = Regex.Match(strFile, $#"(^.{{{i}}})|(godness\w+)(?<=\2(\d+).*?\2)(\d+)");
The regex pattern will look like
(^.{0})|(godness\w+)(?<=\2(\d+).*?\2)(\d+)
^^^
You may try this Concept, where you may use i as parameter and put any value of i.
int i = 0;
string Value =string.Format("(^.{0})|(godness\\w+)(?<=\\2(\\d+).*?\\2)(\\d+)",i);
Match match = Regex.Match(strFile, Value);

How to replace two first characters before underscore with regex?

I have example this string:
HU_husnummer
HU_Adrs
How can I replace HU? with MI?
So it will be MI_husnummer and MI_Adrs.
I am not very good at regex but I would like to solve it with regex.
EDIT:
The sample code I have now and that still does not work is:
string test = Regex.Replace("[HU_husnummer] int NOT NULL","^HU","MI");
Judging by your comments, you actually need
string test = Regex.Replace("[HU_husnummer] int NOT NULL",#"^\[HU","[MI");
Have a look at the demo
In case your input string really starts with HU, remove the \[ from the regex pattern.
The regex is #"^\[HU" (note the verbatim string literal notation used for regex pattern):
^ - matches the start of string
\[ - matches a literal [ (since it is a special regex metacharacter denoting a beginning of a character class)
HU - matches HU literally.
String varString="HU_husnummer ";
varString=varString.Replace("HU_","MI_");
Links
https://msdn.microsoft.com/en-us/library/system.string.replace(v=vs.110).aspx
http://www.dotnetperls.com/replace
using Substring
var abc = "HU_husnummer";
var result = "MI" + abc.Substring(2);
Replace in Regex.
string result = Regex.Replace(abc, "^HU", "MI");

C# replace with regular expression

This code doesn't work, but it works with other expressions, like (?:[A-Za-z][A-Za-z0-9_]*).
The below expression works correctley in a regular expression tester, but it doesn't replace Hello with id in this code:
string test = "int Hello := 2 ;";
string pattern = "\b(?!int|bool)(?:[A-Za-z][A-Za-z0-9_]*)\b";
string replacement = "Id";
Regex rgx = new Regex(pattern);
string newline = rgx.Replace(test, replacement);
You should escape backslashes or use # beginning of your string and make it verbatim string. \b has a special meaning in C# which is backspace, see documentation: Escape Sequences
string pattern = #"\b(?!int|bool)(?:[A-Za-z][A-Za-z0-9_]*)\b";

Categories

Resources