正则表达式提取2个不同的字符和字符串之间的字符串

时间:2022-09-13 13:34:42

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 !

它是ASP.NET C#,如果它有任何区别。提前致谢 !

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.

编辑:公司名称是一个包含可能空格的字符串。用户名没有空格。人物 - 和(仅存在于这两个地方。我认为这是100%明显,因为我给出了这样的例子。

4 个解决方案

#1


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.

链接测试。遍历每一行以查看捕获组。

#2


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


0  

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

你可以观看下面的youtube正则表达式视频,我相信你可以自己回答上面的问题。

http://youtu.be/C2zm0roE-Uc

#4


0  

It's easy to test regexes with grep:

使用grep测试正则表达式很容易:

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

#1


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.

链接测试。遍历每一行以查看捕获组。

#2


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


0  

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

你可以观看下面的youtube正则表达式视频,我相信你可以自己回答上面的问题。

http://youtu.be/C2zm0roE-Uc

#4


0  

It's easy to test regexes with grep:

使用grep测试正则表达式很容易:

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