0

사용 사례 : 특정 형식 (지정된 형식)의 주석이있는 HTML 파일을 가져 와서이 특수 영역을 사용자 정의 JSP 코드로 채우는 JSP 페이지로 변경하십시오 .Groovy Scripting - Regex Replacements - 코드 검토 내 스크립트

간단한 예 : 이미이 문제를 해결 한 지금

<html> 
${someMap['custom-title-content']} 
</html> 

을하지만 스크립트 언어 전력의 일부를 떠 났어요 느낌 도움이되지 수

<html> 
<!-- start:custom-title-content --> 
<h1>this is the generic title content used to develop the HTML page</h1> 
<!-- end:custom-title-content --> 
</html> 

은 렌더링 책상 위에. 내 대본과 비평을 복습 해주십시오.

File folder = new File(/C:\wamp\www\preview/) 
File f = new File(folder, /index.html/) 
assert f.exists() 

//create result so string can be changed while iterating through 
def text = f.getText() 
def result = f.getText() 

//regex to pull section names 
def names = text =~ /(?ms)<!-- ?start:((\w+|-)+) ?-->/ 

//for each matched section name 
names = names.each { 
    //match regex from begining of tag to end of tag 
    def sectionMatcher = text =~ /(?ms)<!-- ?start:(/ + it[1] + /) ?-->.*<!-- ?end:(/ + it[1] + /) ?-->/ 
    def section = sectionMatcher[0][0] // the whole section to be replaced 
    def label = sectionMatcher[0][1] // the name of the value to be replaced with 
    def replacementTag = """\${templateMap['${label}']}""" // the tag needed map key 
    result = result.replace(section, replacementTag) // replace section 
} 

new File(folder, f.getName() + ".replaced") << result //store result in new file 

답변

0

당신은 반복적으로

File folder = new File(/C:\wamp\www\preview/) 
File f = new File(folder, /index.html/) 
assert f.exists() 

//load the template file 
def text = f.getText() 

//regex to pull section names 
def names = text =~ /(?ms)<!-- ?start:((\w+|-)+) ?-->/ 

//for each matched section name, do the replacement, and store the final string in result 
def result = names*.getAt(1).inject(text) { currentTxt, tag -> 
    def sectionMatcher = currentTxt =~ "(?ms)<!-- ?start:($tag) ?-->.*<!-- ?end:($tag) ?-->" 
    currentTxt.replace(sectionMatcher[0][0], "\${templateMap['$tag']}") // replace section 
} 

new File(folder, f.getName() + ".replaced") << result //store result in new file 
(파일에서 얻을 것을) 하나의 문자열을 변경 한 후, 이름 배열의 tagnames 얻을에 주입하는 *. 연산자를 사용하여, 이런 식으로 할 수

틀림없이 귀하의 버전보다 분명하지는 않지만 ;-)