开发者

regular expression in groovy

How to find whether the string cont开发者_运维问答ains '/' as last character .

I need to append / to last character if not present only

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

Mybad thought this is simple, but fails

thanks in advance


The endsWith method posted above works and is probably clear to most readers. For completeness, here's a solution using regular expressions:

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)

The regular expression can be read as:

  • from the start of the line: ^
  • capture a non-greedy group of zero or more characters in length: (.*?)
  • that ends with an optional slash: /?
  • followed by the end of the line: $

The capture group is then all that's returned, so the slash is stripped off if present.


You could use regex, or you could use endsWith("/").


Doesn't this work?

s?.endsWith( '/' )

So...some sort of normalisation function such as:

def normalise( String s ) {
  ( s ?: '' ) + ( s?.endsWith( '/' ) ? '' : '/' )
}

assert '/' == normalise( '' )
assert '/' == normalise( null )
assert 'home/tim/' == normalise( 'home/tim' )
assert 'home/tim/' == normalise( 'home/tim/' )

[edit] To do it the other way (ie: remove any trailing slashes), you could do something like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜