Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regular expression to get last 12 characters of a string (exept spaces)

I want to use a regular expression to capture last 12 characters of a string exept spaces.

2 exemple :

  • COD83 8365 838 BF => D838365838BF
  • COM2893 0409 7642 946 => 304097642946

In c# code, I want to use this :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var input = "COD83 8365 838     BF";
var pattern = "";
var replace = "";
var result = Regex.Replace(input, pattern, replace);

Console.Writeline(input); //print D838365838BF

I read this article but don’t achieve to adapt for me : Regexp to match all the characters except spaces and 4 last characters

Can anyone helps me ?

>Solution :

This would probably be easier without regex.

var input = "COD83 8365 838     BF";
var noSpaces = input.Replace(" ","");
var result = noSpaces.Substring(noSpaces.Length - 12);

however if you wanted plain regex this would work

var input = "COD83 8365 838     BF";
var pattern = ".*(\\w)\\s*(\\w)\\s*(\\w)\\s*(\\w)\\s*(\\w)\\s*(\\w)\\s*(\\w)\\s*(\\w)\\s*(\\w)\\s*(\\w)\\s*(\\w)\\s*(\\w)\\s*$";
var replace = "$1$2$3$4$5$6$7$8$9$10$11$12";
var result = Regex.Replace(input, pattern, replace);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading