0

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.

9
  • 2
    Can username ever contain spaces or parentheses? Commented Oct 13, 2011 at 13:03
  • 2
    Can the company name contain hyphens or parentheses? Commented Oct 13, 2011 at 13:05
  • 2
    Is it guaranteed that the line will end in a fullstop? Commented Oct 13, 2011 at 13:09
  • Come on, more details. As the question is written now, the regex username meets your requirements... Commented Oct 13, 2011 at 13:13
  • @Tim-Pietzcker no spaces in username. Obviously I'd mention it if it was possible. Commented Oct 13, 2011 at 13:16

4 Answers 4

3
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.

Sign up to request clarification or add additional context in comments.

Comments

3
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

3 Comments

You can remove both RegexOptions. And of course this only works if username doesn't contain spaces. Which is a reasonable assumption, therefore +1.
@TimPietzcker Option were forgotten in from previous regex :S. +1 For pointing it out!
This is very good, thank you. Usually usernames don't contain spaces and I didn't mention spaces in question so assumption was good :)
0

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

Comments

0

It's easy to test regexes with grep:

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

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.