Groovy Scripting - Regex Replacements - Code Review My Script -


Use the case: Take an HTML file with the comments in a specific format (I specify the format), and it is a JSP The page that fills in these special areas with custom JSP code.

Simple example:

  & lt; Html & gt; & Lt ;! - Get started: Custom-title-content - & gt; & Lt; H1 & gt; This is the general title material used to develop the HTML page & lt; / H1> & Lt ;! - End Custom-Title-Contents - & gt; & Lt; / Html & gt;  

Render:

  & lt; Html & gt; $ {SomeMap ['custom-title-content']} & lt; / Html & gt;  

Now, I have already solved this problem, but can not help feeling that I have dropped some scripting language power on the table. Please review my script and criticism.

folder = new file (/ C: \ wamp \ www \ preview /) file f = new file (folder, /index.html) .exists () // create results String to def text = f.getText () Def result = f.getText () // regex to repeat section name DP names = text = ~ / (? MS) & lt ;! -? Start: (+ \ w + | -) +)? - & gt; / // Name of each matched section name = names.each {// match regex tag from the beginning of the tag at the end of the tags section. Matter = Text = ~ / (? Ms) & lt ;! - Start: (/ + [[1] + /)? - & gt; * & Lt;!? End (/ + [1] + /)? - & gt; / Def section = sectionMatcher [0] [0] // to change def label = section mater [0] [1] //, the value will be substituted with def substitution = "$ $ {Template}" Necessary map key for '$ {label}']} "" "// tag. Results = result. Rare (section, replacement tag) // replace the section. New file (folder, f.getName () +" .replaced ") & Lt; & Lt; Results // results result in new file

You can do it like this < Code> *. To get tag names in names of operator names, then repeatedly injected by changing a string (which you get from the file)

  file folder = new file ( / C: \ wamp \ www \ preview /) file f = New file (folder, / index.html. Html /) Insert on f.exists () // Load the template file DH text = f.getText () // To drag the regex section name DF names = text = ~ / (? MS) & lt ;! -? Start: ((\ w + | -) +)? - & gt; / // For each matched section name, substitute, and the final string is defined as DEF result = names * .getAt (1). Injection (text) {currentTxt, tag - & gt; Def sectionMatcher = currentTxt = ~ (? MS) & lt ;! - Start: ($ Tag)? - & gt;. * & Lt ;! - end: ($ tag)? - & gt; CurrentTxt.replace (sectionMatcher [0] [0], "\ $ {templateMap ['$ tag']}") // replacement section} new file (folder, f.getName () + ".replaced") & lt; & Lt; Results // result result in new file  

This is clearly less obvious than your version; -)


Comments