Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to get last 3 characters of a string

Tags:

c#

regex

I want to write a regular expression which will take only last 3 char of a string and append some constant string to it.

I am using C#. I am trying to make regular expression as database entry. Later Read this entry in application and do the transformation based on regex in C#.

Something like :

stringVal.Trim().Substring(0, stringVal.Trim().Length - 3) + ".ConstantValue"
like image 824
Cannon Avatar asked Jan 06 '14 16:01

Cannon


2 Answers

Use this regular expression :

.{3}$

If you want to avoid spaces at end and can use capturing groups (you didn't precise the language or regex flavour), use

(.{3})\s*$

But note that there's no obvious reason to use a regex here instead of slicing the string.

like image 112
Denys Séguret Avatar answered Oct 05 '22 01:10

Denys Séguret


w{3}$




w or \w (vary in different language)

Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to [A-Za-z0-9_]. For example, /\w/ matches "a" in "apple", "5" in "$5.28", "3" in "3D" and "m" in "Émanuel".

x{n}

Where "n" is a positive integer, matches exactly "n" occurrences of the preceding item "x". For example, /a{2}/ doesn't match the "a" in "candy", but it matches all of the "a"'s in "caandy", and the first two "a"'s in "caaandy".

$

Matches the end of input. If the multiline flag is set to true, also matches immediately before a line break character. For example, /t$/ does not match the "t" in "eater", but does match it in "eat".

like image 27
MD SHAYON Avatar answered Oct 05 '22 00:10

MD SHAYON