tags:

views:

72

answers:

3

How to find whether the string contains '/' 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

+2  A: 

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

http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/lang/String.html#endsWith%28java.lang.String%29

glowcoder
+1  A: 

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/' )
tim_yates
thanks. mybad forgot the method
Srinath
@tim, how to remove / from last character if present only. i'm handling two cases in different scenarios. should omit / in last character.ex: /home/tim/ should produce /home/tim . thanks
Srinath
updated my answer for removing trailing slashes
tim_yates
@tim, thanks a lot.
Srinath
+1  A: 

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.

Ted Naleid
thanks ted for providing solutions
Srinath