Reputation: 3305
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
Reputation: 195079
It's easy to test regexes with grep:
kent$ echo "COMPANY NAME - username (Name Surname)."|grep -Po '(?<=- ).*(?= \()'
username
Upvotes: 0
Reputation: 28596
You can watch the below youtube regular expression video , i am sure the above question you can answer it yourself.
Upvotes: 0
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
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