user542103
user542103

Reputation: 265

Regex transform for Java code with Notepad++ - date .format to SimpleDateFormat

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

Answers (2)

user12097764
user12097764

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

Toto
Toto

Reputation: 91508

Be aware that in Notepad++ the parenthesis have to be escaped in the replacement part.

  • Ctrl+H
  • Find what: (\w+)\.format\((.+?)\)
  • Replace with: \(new SimpleDateFormat\($2\).format\($1\)\)
  • CHECK Match case
  • CHECK Wrap around
  • CHECK Regular expression
  • UNCHECK . matches newline
  • Replace all

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):

enter image description here

Screen capture (after):

enter image description here

Upvotes: 1

Related Questions