0

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

I want to split this string on the first appearance on # and , i.e 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?

2

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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();

Comments

1

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);

Comments

0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.