Tim Kelly
Tim Kelly

Reputation: 33

Regular expression to extract based on capital letters

Hi please can someone help with a C# regex to split into just two words as follows:

"SetTable" ->> ["Set", "Table"]
"GetForeignKey" ->> ["Get", "ForeignKey"]  //No split on Key!

Upvotes: 0

Views: 96

Answers (2)

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30545

Try the regex below

(?![A-Z][a-z]+Key)[A-Z][a-z]+|[A-Z][a-z]+Key

code

var matches = Regex.Matches(input, @"(?![A-Z][a-z]+Key)[A-Z][a-z]+|[A-Z][a-z]+Key");
        foreach (Match match in  matches)
            match.Groups[0].Value.Dump();

for Splitting

matches.OfType<Match>().Select(x => x.Value).ToArray().Dump();      

Fiddle

Upvotes: -1

ES2018
ES2018

Reputation: 438

This can be solved in different ways; one method is the following

string source = "GetForeignKey";

var result = Regex.Matches(source, "[A-Z]").OfType<Match>().Select(x => x.Index).ToArray();
string a, b;
if (result.Length > 1)
{
    a = source.Substring(0, result[1]);
    b = source.Substring(result[1]);
}

Upvotes: 2

Related Questions