yosh
yosh

Reputation: 3305

Regex to extract string between 2 different characters and strings

Short question, but can't make it work. I have a string:

COMPANY NAME - username (Name Surname).

What kind of regex will give me username (without spaces) from between - and ( in such example?

It's ASP.NET C# if it makes any difference. Thanks in advance !

EDIT : The company name is a string with possible spaces. Username is without spaces. The characters - and ( are present only in these 2 places. I thought it was 100% obvious since I gave such example.

Upvotes: 0

Views: 768

Answers (4)

Kent
Kent

Reputation: 195079

It's easy to test regexes with grep:

kent$  echo "COMPANY NAME - username (Name Surname)."|grep -Po '(?<=- ).*(?= \()'
username

Upvotes: 0

Shivprasad Koirala
Shivprasad Koirala

Reputation: 28596

You can watch the below youtube regular expression video , i am sure the above question you can answer it yourself.

http://youtu.be/C2zm0roE-Uc

Upvotes: 0

xanatos
xanatos

Reputation: 111860

var match = Regex.Match(
    "COMPANY - ltd (NAME) - username (Name Surname)", 
    @"^.* - (.*?) \(.*\)$"
);
var username = match.Groups[1].Value;

If your line ends with a . then the Regex is @"^.* - (.*?) \(.*\)\.$"

Through the use of .*? (the lazy quantifier) this Regex is quite resistant to strange "things" like the one I'm using as a test.

Link with tests. Pass over each row to see the capture group.

Upvotes: 3

FailedDev
FailedDev

Reputation: 26930

string resultString = null;
try {
    resultString = Regex.Match(subjectString, @"-\s+(\S*)\s*\(").Groups[1].Value;
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

Output : username

Upvotes: 3

Related Questions