Cannon
Cannon

Reputation: 2783

Regular expression to get last 3 characters of a string

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"

Upvotes: 20

Views: 75045

Answers (2)

MD SHAYON
MD SHAYON

Reputation: 8051

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".

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382150

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.

Upvotes: 39

Related Questions