regex for PropertyName e.g. HelloWorld2HowAreYou would get Hello HelloWorld2 HelloWorld2How
I need a regex for PropertyName e.g. HelloWorld2HowAreYou
would get:
Hello开发者_运维百科 HelloWorld2 HelloWorld2How etc.
I want to use it in C# [A-Z][a-z0-9]+
would give you all words that start with capital letter. You can write code to concat them one by one to get the complete set of words.
For example matching [A-Z][a-z0-9]+
against HelloWorld2HowAreYou
with global flag set, you will get the following matches.
Hello
World2
How
Are
You
Just iterate through the matches and concat them to form the words.
Port this to C#
var s = "HelloWorld2HowAreYou";
var r = /[A-Z][a-z0-9]+/g;
var m;
var matches = [];
while((m = r.exec(s)) != null)
matches.push(m[0]);
var o = "";
for(var i = 0; i < matches.length; i++)
{
o += matches[i]
console.log(o + "\n");
}
I think something like this is what you want:
var s = "HelloWorld2HowAreYou";
Regex r = new Regex("(?=[A-Z]|$)(?<=(.+))");
foreach (Match m in r.Matches(s)) {
Console.WriteLine(m.Groups[1]);
}
The output is (as seen on ideone.com):
Hello
HelloWorld2
HelloWorld2How
HelloWorld2HowAre
HelloWorld2HowAreYou
How it works
The regex is based on two assertions:
(?=[A-Z]|$)
matches positions just before an uppercase, and at the end of the string(?<=(.+))
is a capturing lookbehind for.+
behind the current position into group 1
Essentially, the regex translates to:
- "Everywhere just before an uppercase, or at the end of the string"...
- "grab everything behind you if it's not an empty string"
精彩评论