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.