Formatting a substring to get all characters after the first underscore, but before the second underscore?

for example, we have this line:

  • hello_my is__b_name

and want to get only part of my name, how can I get it just with a substring?

In addition, the format in the example will always be the same, so I just need to get what after the first underline, but before the second underline.

+5
source share
3 answers

string.Splitwill be for this, no need to enter Substring:

var parts = "hello_my name_is_bob".Split('_');

string name = parts[1] // == "my name";

Or, in one liner (although I find this less readable):

string name = "hello_my name_is_bob".Split('_')[1];
+14
source
"hello_my name_is_bob".Split('_').Skip(1).First();
+2
source

If you know for sure that you have two underscores, use this code:

var pos = str.IndexOf('_');
var last = str.IndexOf('_', pos+1);
var res = str.Substring(pos+1, last-pos-1);

This will fail if the number of underscores is less than two.

+1
source

All Articles