user1497590
user1497590

Reputation: 145

RegEx how to get domain from domain\username

RegEx to get domain from domain\username. I tried this but it returns the entire string.

/^(.*?)\.\\/

What am I doing incorrectly? the end result should be domain

Upvotes: 0

Views: 1407

Answers (3)

wellnoidea
wellnoidea

Reputation: 193

^(.*?)\\

Will give you domain\

^.[^\\]*

Will give you domain

[^x] gives you everything but x and \ has to be escaped likeso \\.

Upvotes: 0

Cory Nelson
Cory Nelson

Reputation: 30011

Regex is quite the large hammer for such a tiny nail. Just use IndexOf.

string domain = str.SubString(0, str.IndexOf('\\'));

Upvotes: 5

Ben
Ben

Reputation: 2917

If you insist on using regular expressions then what you are doing wrong is that you are are not escaping the \ (I'm also not sure why the . is there) Try

/^(.*?)\\.*$/

However for such a simple problem you would be better served just using .IndexOf to find the \ and then .Substring to return everything before it.

Upvotes: 0

Related Questions