Line 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 a way to put the separator in the template instead ([-])

?

+3


source to share


3 answers


You can use string interpolation :

string first = "2-18;1-4; 5-212; 4-99" ;
Char delimiter = '-';

String pattern = $@"\s?(\d+)([{delimiter}])(\d+)";

      

The sign $

(which must be before @

) allows you to put a variable (string) in a string with{

}

Note: In older versions of C # this will not work

In this case, you can use string.Format :

string.Format(@"\s?(\d+)([{0}])(\d+)", delimiter);

      



This works the same, but uses the number of placeholders for parameters after ,


Regex.Escape : (Credits to NtFreX)

Also, if you are using a regex, you should avoid your character (because they might mean something else in the regex).

$@"\s?(\d+)([{Regex.Escape( delimiter.ToString() )}])(\d+)";

      

+8


source


This is the 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 versions of C #):

Char delimiter = '-';

String pattern = $@"\s?(\d+)([{delimiter}])(\d+)";

      

+2


source


Additionally I used Regex.Escape

to avoid the separator.

$@"\s?(\d+)([{Regex.Escape(delimiter)}])(\d+)";

      

For example, if the delimiter .

, you need to change it to \.

because it .

is a special regex character that matches any character. The same goes for other characters.

+2


source







All Articles