如何查找字符串是否包含'/'作爲最後一個字符。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