我有一个像这样的文本字符串:
def ctext = """This is the normal text.
This is the again normal text.
<code>int main(){
printf('Hello World!\n');
return 0;}
</code>
This is the again normal text.
This is the again normal text.
<code>
public static void main (String args[]){
System.out.println('Hello World!\n');
return 0;}
</code>
The last line ....
"""
Run Code Online (Sandbox Code Playgroud)
我想'<code>(.*)</code>'通过将此方法传递给类似的方法来替换该节之间的所有文本doBeautify(codeText).
我这样想,但没有运气:
def matches = ctext =~ /<code>(.*)<\/code>/
Run Code Online (Sandbox Code Playgroud)
任何帮助appriciated.谢谢
默认情况下,.不匹配\r和\n.尝试:
def matches = ctext =~ /(?s)<code>(.*?)<\/code>/
Run Code Online (Sandbox Code Playgroud)
在哪里(?s)被称为DOT-ALL修饰符(使.匹配任何东西).我也.*通过放置?它而使非贪婪.否则,它会匹配第一个<code>和最后一个</code>(以及介于两者之间的所有内容).
如果您的输入如下所示,请意识到正则表达式会中断:
<code>int main(){
printf('Hello </code> World!\n');
</code>
Run Code Online (Sandbox Code Playgroud)
仅举几个角落案例中的一个.在这种情况下,您需要一个适合您语言的解析器.
一个小小的演示:
def ctext = """This is the normal text.
This is the again normal text.
<code>int main(){
printf('Hello World!\\n');
return 0;}
</code>
This is the again normal text.
This is the again normal text.
<code>
public static void main (String args[]){
System.out.println('Hello World!\\n');
return 0;}
</code>
The last line ....
"""
def matches = ctext =~ /(?s)<code>(.*?)<\/code>/
matches.each { println it[1] }
Run Code Online (Sandbox Code Playgroud)
生产:
int main(){
printf('Hello World!\n');
return 0;}
public static void main (String args[]){
System.out.println('Hello World!\n');
return 0;}
可以在http://ideone.com/JQ0Ck上进行测试