Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String pattern delimiter

Tags:

c#

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 ([-]) ?

like image 507
Sanimys Avatar asked Sep 25 '26 20:09

Sanimys


2 Answers

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+)";
like image 126
EpicKip Avatar answered Sep 27 '26 08:09

EpicKip


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+)";
like image 28
Romano Zumbé Avatar answered Sep 27 '26 08:09

Romano Zumbé



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!