简体   繁体   中英

Regex .NET match everything until first space + letter is found

I have:

01 - Radio N Am 2007 
186508980X -16-17 - Horns and Bones
(ab)normal - constitutions

Goal:

Radio N Am 2007 
Horns and Bones
constitutions

I tried with

^(?:(?!(?:\S*[\s[a-z][A-Z])).)+

but the output is:

 - Radio N Am 2007
 - Horns and Bones

Please help me with a correct regex to achieve the goal.

Instead of trying to replace, match what you want with:

(?<= )[A-Za-z].*

demo

Search for:

^.*?- (?=[A-Za-z])

and replace by empty string.

RegEx Demo

If you are looking for a regex solution that will only match the substrings after the last - , you can just use

-\s*([^-]*$)

See demo

If there must be a letter after the hyphen , you may use -\\s*(\\p{L}[^-]*$) . The \\p{L} construct will match any Unicode letter.

在此处输入图片说明

C# IDEONE demo :

var lines = new string[] {"01 - Radio N Am 2007", 
"186508980X -16-17 - Horns and Bones",
"(ab)normal - constitutions"};
foreach (string s in lines) 
{
    var matches = Regex.Matches(s, @"-\s*([^-]*$)");
    foreach (Match m in matches)
        Console.WriteLine(m.Groups[1].Value);
}

But you can also use a non-regex approach if you need to get substrings after the last hyphen:

Console.WriteLine(s.Substring(s.LastIndexOf("-") + 1).Trim());

See another demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM