Reputation: 265
I need to do some re-factoring on my Java code. I need to turn this:
X.format("Z")
into this:
(new SimpleDateFormat("Z").format(X))
Examples:
dateStart.format("yyyy-MM-dd HH:mm")
into
(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(dateStart))
reportStart.format("yyyy-MM")
into
(new SimpleDateFormat("yyyy-MM").format(reportStart))
I'm thinking to use Notepad++ find/replace, but I'm not good with Regex, and hoping someone would know easily?
I've tried variations of the below, and the closest I've got is with the one below... But with the one below, it wants to take everything to the left of .format and treat that as $1
find:([^)]*)\.format\(([^)]*)\)
replace with:
(new SimpleDateFormat($2.format($1))
Upvotes: 0
Views: 213
Reputation:
Probably a simple find / replace will work like this :
Find (?s)(\w+)\.format\((.*?)\)
update Escape the parenthesis when used as literals because Boost::regex uses these characters as special operators in the replacement, format string.
Boost-Extended format strings treat all characters as literals except for '$', '\', '(', ')', '?', and ':'
Replace \(new SimpleDateFormat\($2\).format\($1\)\)
https://regex101.com/r/f77yBt/1
If interested in why certain characters need to be escaped to be considered
literals, see this :
https://www.boost.org/doc/libs/1_70_0/libs/regex/doc/html/boost_regex/format/boost_format_syntax.html
Essentially, boost::regex uses these characters to implement a pseudo-callback
that does simple (possibly nested) conditionals checking if a group matched
and taking a yes : no
replacement action.
Upvotes: 1
Reputation: 91508
(\w+)\.format\((.+?)\)
\(new SimpleDateFormat\($2\).format\($1\)\)
. matches newline
Explanation:
(\w+) # group 1, 1 or more word characters
\. # a dot
format\( # literally
(.+?) # group 2, 1 or more any character but newline, not greedy
\)
Screen capture (before):
Screen capture (after):
Upvotes: 1