2010-07-20 52 views
1

如何查找字符串是否包含'/'作爲最後一個字符。groovy中的正則表達式

我需要追加/到最後一個字符,如果不存在,只有

ex1 : def s = home/work 
    this shuould be home/work/  
ex2 : def s = home/work/ 
    this will remain same as home/work/ 

Mybad認爲這是簡單的,但事先無法

感謝

+0

解決:應使用endsWith('/')。謝謝你的意見 – Srinath 2010-07-20 13:50:13

回答

1

這不工作?

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/') 
+0

謝謝。 mybad忘記了方法 – Srinath 2010-07-20 13:49:05

+0

如何刪除/從最後一個字符,如果只存在。我在不同的場景下處理兩個案例。應該省略/在最後一個字符中。 例如:/ home/tim /應該產生/ home/tim。謝謝 – Srinath 2010-07-20 15:48:15

+0

更新我的答案,以消除尾部斜槓 – 2010-07-20 17:59:29

3

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) 
    

    正則表達式可以理解爲或更多字符長度:(.*?)

  • 以可選斜槓結尾:/?
  • 後面跟着行尾:$

捕獲組是所有返回的,所以斜槓如果存在則被剝離。

+0

謝謝提供解決方案 – Srinath 2010-07-22 09:47:17