简体   繁体   中英

Split a string in between two characters in C#

I have a string of type "24;#usernamehere,#AWRFR\\user,#,#,#usernamehere"

I want to split this string on the first appearance on # and , ie i want a string to be fetched which is inbetween these two characters.

So for the above string i want the OUTPUT as:

usernamehere

How can i split a string in between two characters using Regex function?

A simple Regex Pattern might do the job:

var pattern = new System.Text.RegularExpressions.Regex("#(?<name>.+?),");

test:

string s = @"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
pattern.Match(s).Groups["name"].Value;   //usernamehere

Using Linq:

using System.Linq;
var input = @"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";

You can split it with a single line:

var x = input.Split('#').Where(e => e.Contains(',')).Select(e => e.Split(',').First());

which is the same as:

var x = from e in input.Split('#') 
        where e.Contains(',') 
        select e.Split(',').First();

in both cases the result would be:

x = {"usernamehere", "AWRFR\user", "", ""}

Which is exactly an array with all substrings enclosed by # and , . Then if you want the first element just add .First() or do:

x.First();

You need to find the first index of '#' & ','. Then use substring method to get your required trimmed string. Read this for more details on substring method

string s = @"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
string finalString = s.Substring(s.IndexOf('#') + 1, s.IndexOf(',') - s.IndexOf('#') - 1);

Not exactly the way you asked for it, but should do what you want...

string input = @"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
string username = input.Substring(input.LastIndexOf("#") + 1);

If you wanted you could get the position of the first # and the ,

int hashPosition = input.IndexOf("#") + 1;
int commaPosition = input.IndexOf(",");

string username = input.Substring(hashPosition, commaPosition - hashPosition));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM