2010-07-20 43 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