Regular expression: extract last 2 characters

What is the best way to extract the last 2 characters of a string using a regular expression.

For example, I want to extract a status code from the following

"A_IL"

I want to extract IL as a string.

please provide me the C # code on how to get it.

string fullexpression = "A_IL"; string StateCode = some regular expression code.... 

thanks

+6
regex
source share
2 answers

Use regex:

  ..$ 

This will cause two characters to appear next to the end anchor.

Since you are using C #, it will be simpler and probably faster:

 string fullexpression = "A_IL"; string StateCode = fullexpression.Substring(fullexpression.Length - 2); 
+21
source share

Use /(..)$/ , then pull group 1 ( .groups(1) , $1 , \1 , etc.).

+3
source share

All Articles