Java regexp: splitting on "/" that is not at the beginning of a string
I want to split a/bc/de/f
as [a, bc, de, f]
but /a/bc/de/f
as [/a, bc, de, f]
.
Is there a way to split on /
which is not at the beginning of the str开发者_高级运维ing? (I'm having a bad Regexp day.)
(?!^)/
seems to work:
public class Funclass{
public static void main(String [] args) {
String s = "/firstWithSlash/second/third/forth/fifth/";
String[] ss = s.split("(?!^)/");
for (String s_ : ss)
System.out.println(s_);
}
}
output:
/firstWithSlash
second
third
forth
fifth
As @user unknown commented, this seems to be a wrong expression, it should be (?<!^)/
to indicate negative lookbehind.
The simplest solution is probably just to split s.substring(1)
on /
, and then prepend s.charAt(0)
to the first result.
Other than that, since the split regex is not anchored, it would be challenging to do. You'd want to split on "something that isn't the start of the line, followed by a slash" - i.e. [^^ ]/
- but this would mean that the character preceding the slash was stripped out too. In order to do this you'd need negative look-behind, but I don't think that syntax is supported in the String.split regexes.
Edit: According to the Pattern javadocs it seems that Java does support negative lookbehind, and the following regex may do the job:
s.split("(?<!^)/");
A quick test indicates that this does indeed do what you want.
Couldn't you just add a check at the beginning to see if there's a slash in the beginning?
if( str.charAt(0) == '/' ) {
arr = str.substring(1).split( "/" );
arr[0] = "/"+arr[0];
} else
arr = str.split( "/" );
Or a little simpler:
arr = str.charAt(0) + str.substring(1).split( "/" );
If the first is a slash, it'll just slap on a slash at the beginning of the first token. If there's only one character in the first token (that doesn't begin with a slash), then the first array element is the empty string and it'll still work.
精彩评论