11// grepWin - regex search and replace for Windows
22
3- // Copyright (C) 2011, 2015 - Stefan Kueng
3+ // Copyright (C) 2011, 2015, 2024 - Stefan Kueng
44
55// This program is free software; you can redistribute it and/or
66// modify it under the terms of the GNU General Public License
1818//
1919#include " stdafx.h"
2020#include " RegexReplaceFormatter.h"
21+
22+ std::wstring ExpandString (const std::wstring& replaceString)
23+ {
24+ // ${now,formatString}
25+ wchar_t buf[4096 ] = {};
26+ GetDateFormat (LOCALE_USER_DEFAULT , DATE_SHORTDATE , nullptr , nullptr , buf, _countof (buf));
27+ std::wstring dateStr = buf;
28+ GetTimeFormat (LOCALE_USER_DEFAULT , 0 , nullptr , nullptr , buf, _countof (buf));
29+ dateStr += L" - " ;
30+ dateStr += buf;
31+ std::time_t now = std::chrono::system_clock::to_time_t (std::chrono::system_clock::now ());
32+ UINT syntaxFlags = boost::regex::normal;
33+ boost::wregex expression = boost::wregex (L" \\ $\\ {now\\ s*,?([^}]*)\\ }" , syntaxFlags);
34+ boost::match_results<std::wstring::const_iterator> whatC;
35+ boost::match_flag_type matchFlags = boost::match_default | boost::format_all;
36+ auto resultString = replaceString;
37+ SearchReplace (resultString, L" ${now}" , dateStr);
38+
39+ try
40+ {
41+ auto start = resultString.cbegin ();
42+ auto end = resultString.cend ();
43+ while (regex_search (start, end, whatC, expression, matchFlags))
44+ {
45+ if (whatC[0 ].matched )
46+ {
47+ auto fullMatch = whatC.str ();
48+
49+ std::wstring formatStr;
50+ if (whatC.size () > 1 )
51+ {
52+ formatStr = whatC[1 ].str ();
53+ if (!formatStr.empty ())
54+ {
55+ std::wstring formattedDateStr (4096 , ' \0 ' );
56+ struct tm locTime;
57+ _localtime64_s (&locTime, &now);
58+ try
59+ {
60+ std::wcsftime (&formattedDateStr[0 ], formattedDateStr.size (), formatStr.c_str (), &locTime);
61+ SearchReplace (resultString, fullMatch, formattedDateStr);
62+ }
63+ catch (const std::exception&)
64+ {
65+ }
66+ }
67+ }
68+ else
69+ {
70+ SearchReplace (resultString, fullMatch, dateStr);
71+ }
72+ }
73+ if (start == whatC[0 ].second )
74+ {
75+ if (start == end)
76+ break ;
77+ ++start;
78+ }
79+ else
80+ start = whatC[0 ].second ;
81+ }
82+ }
83+ catch (const std::exception&)
84+ {
85+ }
86+ return resultString;
87+ }
0 commit comments