2

I have a string and I want to get the words after the last dot . in the string.

Example:

string input = "XimEngine.DynamicGui.PickKind.DropDown"; 

Result:

DropDown 
1
  • 1
    string result = input.SubString(input.LastIndexOf('.') + 1); Commented Aug 1, 2019 at 12:39

3 Answers 3

7

There's no need in Regex, let's find out the last . and get Substring:

 string result = input.Substring(input.LastIndexOf('.') + 1); 

If input doesn't have . the entire input will be returned.

Edit: Same code rewritten with a help of range:

string result = input[(input.LastIndexOf('.') + 1)..]; 

Finally, if you insist on regular expression, you can put it as

string result = Regex.Match(input, "[^.]*$", RegexOptions.RightToLeft).Value; 

We match zero or more symbols which are not dot . starting from the end of the string (from the right).

Sign up to request clarification or add additional context in comments.

2 Comments

This is written with thinking about performance. It will work faster than input.Split('.').Last();
This should have been the accepted answer.
4

Not a RegEx answer, but you could do:

var result = input.Split('.').Last(); 

Comments

0

In Regex you can tell the parser to work from the end of the string/buffer by specifying the option RightToLeft.

By using that we can just specify a forward pattern to find a period (\.) and then capture (using ( )) our text we are interested into group 1 ((\w+)).

var str = "XimEngine.DynamicGui.PickKind.DropDown"; Console.WriteLine(Regex.Match(str, @"\.(\w+)", RegexOptions.RightToLeft).Groups[1].Value); 

Outputs to console:

DropDown 

By working from the other end of the string means we don't have to deal with anything at the beginning of the string to where we need to extract text.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.