下面的代码应该可以提取这三个属性中的每一个。首先,请注意我正在加载整个 xml 文件。没有必要像您一样提取特定的行。其次,我把它写得足够灵活,允许在Server
属性中换行并允许属性的任何顺序。
我看到你特别在正则表达式上苦苦挣扎。为了您的理解,我将分解第一个正则表达式:
(?s) // DOTALL flag. Causes the . wildcard to match newlines.
\x3c // The < character. For reasons I don't understand, `propertyregex` doesn't allow <
Server // Match 'Server' literally
.*? // Reluctantly consume characters until...
name= // 'name=' is reached
" // Because ant is an XML file, we must use this escape sequence for "
(.*?) // Reluctantly grab all characters in a capturing group until...
" // another double quote is reached.
最后是 XML:
<loadfile property="server.details" srcfile="${baseDir}/build/myTest.xml"/>
<propertyregex property="server.name"
input="${server.details}"
regexp="(?s)\x3cServer.*?name="(.*?)""
select="\1" />
<propertyregex property="server.value"
input="${server.details}"
regexp="(?s)\x3cServer.*?value="(.*?)""
select="\1" />
<propertyregex property="server.port"
input="${server.details}"
regexp="(?s)\x3cServer.*?port="(.*?)""
select="\1" />