如何查找字符串是否包含'/'作为最后一个字符。groovy中的正则表达式
我需要追加/到最后一个字符,如果不存在,只有
ex1 : def s = home/work
this shuould be home/work/
ex2 : def s = home/work/
this will remain same as home/work/
Mybad认为这是简单的,但事先无法
感谢
如何查找字符串是否包含'/'作为最后一个字符。groovy中的正则表达式
我需要追加/到最后一个字符,如果不存在,只有
ex1 : def s = home/work
this shuould be home/work/
ex2 : def s = home/work/
this will remain same as home/work/
Mybad认为这是简单的,但事先无法
感谢
你可以使用正则表达式,或者你可以使用endsWith("/")
。
这不工作?
s?.endsWith('/')
所以......某种标准化的功能,如:
def normalise(String s) {
(s ?: '') + (s?.endsWith('/') ? '' : '/')
}
assert '/' == normalise('')
assert '/' == normalise(null)
assert 'home/tim/' == normalise('home/tim')
assert 'home/tim/' == normalise('home/tim/')
[编辑]做它的其他方式(如:删除任何尾随斜杠),你可以这样做这样的事情:
def normalise(String path) {
path && path.length() > 1 ? path.endsWith('/') ? path[ 0..-2 ] : path : ''
}
assert '' == normalise('')
assert '' == normalise('/')
assert '' == normalise(null)
assert 'home/tim' == normalise('home/tim')
assert 'home/tim' == normalise('home/tim/')
endsWith方法张贴上面的作品,并可能为大多数读者清楚。为了完整性,这里是使用正则表达式的解决方案:从该行的开始
^
def stripSlash(str) {
str?.find(/^(.*?)\/?$/) { full, beforeSlash -> beforeSlash }
}
assert "/foo/bar" == stripSlash("/foo/bar")
assert "/baz/qux" == stripSlash("/baz/qux/")
assert "quux" == stripSlash("quux")
assert null == stripSlash(null)
正则表达式可以理解为或更多字符长度:(.*?)
/?
$
捕获组是所有返回的,所以斜杠如果存在则被剥离。
谢谢提供解决方案 – Srinath 2010-07-22 09:47:17
解决:应使用endsWith('/')。谢谢你的意见 – Srinath 2010-07-20 13:50:13