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+)";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With