code_junkie

Add 10000 to numbers using Regex replace?

Nov 11th, 2011
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. Photo.123.aspx
  2.  
  3. Photo.10123.aspx
  4.  
  5. Photo.12.aspx
  6.  
  7. Photo.10012.aspx
  8.  
  9. using System;
  10. using System.Text.RegularExpressions;
  11.  
  12. namespace RenameAspxFile
  13. {
  14. sealed class Program
  15. {
  16. private static readonly Regex _aspxFileNameRegex = new Regex(@"(S+.)(d+)(.aspx)", RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
  17. private static readonly string[] _aspxFileNames= {"Photo.123.aspx", "Photo.456.aspx", "BigPhoto.789.aspx"};
  18.  
  19. static void Main(string[] args)
  20. {
  21. Program program = new Program();
  22. program.Run();
  23. }
  24.  
  25. void Run()
  26. {
  27. foreach (string aspxFileName in _aspxFileNames)
  28. {
  29. Console.WriteLine("Renamed '{0}' to '{1}'", aspxFileName, AddTenThousandToPhotoNumber(aspxFileName));
  30. }
  31. }
  32.  
  33. string AddTenThousandToPhotoNumber(string aspxFileName)
  34. {
  35. return _aspxFileNameRegex.Replace(aspxFileName, match => String.Format("{0}{1}{2}", match.Result("$1"), Int32.Parse(match.Result("$2")) + 10000, match.Result("$3")));
  36. }
  37. }
  38. }
  39.  
  40. s(
  41. Photo. (d{2,3}) .aspx
  42. ){
  43. "Photo." . ($1 + 10000) . ".aspx"
  44. }xe
  45.  
  46. "Photo./d.aspx" and replace with "Photo.1000$1.aspx"
  47. "Photo./d/d.aspx" and replace with "Photo.100$1.aspx"
  48. "Photo./d/d/d.aspx" and replace with "Photo.10$1.aspx"
  49.  
  50. Regex regex = new Regex(@"(ddd?)", RegexOptions.None);
  51. string result = regex.Replace(@"Photo.123.asp", delegate(Match m)
  52. {
  53. return "Photo.1"
  54. + m.Groups[1].Captures[0].Value.PadLeft(4, '0')
  55. + ".aspx";
  56. }
  57. );
  58.  
  59. static public string Evaluator(Match match)
  60. {
  61. return "Photo.1"
  62. + match.Groups[1].Captures[0].Value.PadLeft(4, '0')
  63. + ".aspx";
  64. }
  65.  
  66. public void Code(params string[] args)
  67. {
  68. string pattern = @"Photo.([d]+).aspx";
  69. string test = "Photo.123.aspx";
  70. Regex regex = new Regex(pattern);
  71. string converted = regex.Replace(test, Evaluator)
  72. Console.WriteLine(converted);
  73. }
  74.  
  75. [^d][d]{2,3}[^d]
  76.  
  77. :s/Photo.d+.aspx/=Photo.submatch(0)+10000.aspx/g
Add Comment
Please, Sign In to add comment