版权声明:本文为博主chszs的原创文章,未经博主允许不得转载。 https://blog.csdn.net/chszs/article/details/8841661
用Groovy思考 第五章 Groovy特性深入(2)
作者:chszs,转载需注明。博客主页:http://blog.csdn.net/chszs6. 斜线字符串
正如早先提到的,斜线可以用于定义字符串。用斜线定义字符串有一个优点:那就是,字符串本身的内容无需转义反斜线。比如:
def winpathQuoted = 'C:\\windows\\system32'
def winpathSlashy = /C:\windows\system32/
println winpathSlashy // C:\windows\system32
assert winpathSlashy ==~ '\\w{1}:\\\\.+\\\\.+'
assert winpathSlashy ==~ /\w{1}:\\.+\\.+/
7. 多行斜线字符串
斜线字符串还能够跨越多行。这一点对于多行正则表达式非常有用。比如:
def name = "vishal"
def path = "c:/groovy/"
def multilineslashy = /
Hello $name
path $path
dollar = $
path = c:\/groovy
/
println multilineslashy
输出为:
Hello vishal
path c:/groovy/
dollar = $
path = c:/groovy
8. 斜线字符串中的美元符号$
在多行斜线字符串中,如果字符串内出现斜线/,那么它需要被转义。另外,如果字符串内出现了$美元符号(没有用于表达式时),也需要转义,否则会报MissingPropertyException异常。比如:
def name = "vishal"
def path = "c:/groovy"
def multilineSlashy = /
Hello $name
path = $path
dollar = $test
path = c:\/groovy
/
println multilineSlashy
输出:
Exception thrown
四月 17, 2013 9:11:24 下午 org.codehaus.groovy.runtime.StackTraceUtils sanitize
WARNING: Sanitizing stacktrace:
groovy.lang.MissingPropertyException: No such property: test for class: ConsoleScript3
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:49)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:231)
at ConsoleScript3.run(ConsoleScript3:3)
at groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:257)
at groovy.lang.GroovyShell.run(GroovyShell.java:481)
at groovy.lang.GroovyShell.run(GroovyShell.java:163)
at groovy.lang.GroovyShell$run.call(Unknown Source)
at groovy.ui.Console$_runScriptImpl_closure17.doCall(Console.groovy:951)
at groovy.ui.Console$_runScriptImpl_closure17.doCall(Console.groovy)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:909)
at groovy.lang.Closure.call(Closure.java:411)
at groovy.lang.Closure.call(Closure.java:405)
at groovy.lang.Closure.run(Closure.java:492)
at java.lang.Thread.run(Thread.java:722)
groovy.lang.MissingPropertyException: No such property: test for class: ConsoleScript3
at ConsoleScript3.run(ConsoleScript3:3)