Reputation: 119
I need to split a string in java with a regex, but i'm not quite sure how to. I have to split
[Caps][RCaps]C[Caps][RCaps]atalog[Caps][RCaps]
By the words inside the square brackets. I somehow need to get all the parts of the string.
Expected output:
[Caps]
[RCaps]
C
[Caps]
[RCaps]
atalog
[Caps]
[RCaps]
And the text inside the square brackets could be whatever. In this case, it is "Caps" and "RCaps" but it could also be "Potato" for example
Upvotes: 0
Views: 285
Reputation: 708
try this.
String string = "[Caps][RCaps]C[Caps][RCaps]atalog[Caps][RCaps]";
String[] split = string.split("\\]");
for (String string1 : split) {
if (string1.charAt(0) != '[') {
int indexOf = string1.indexOf("[");
String substring = string1.substring(0, indexOf);
String substring1 = string1.substring(indexOf, string1.length()) + "]";
System.out.println(substring);
System.out.println(substring1);
} else {
System.out.println(string1 + "]");
}
}
Upvotes: 1
Reputation: 7804
"["
or "]"
are regex matching characters called meta-characters. You need to add escape char before it. \\[
or \\]
You need to try something like this:
String str = "[Caps][RCaps]C[Caps][RCaps]atalog[Caps][RCaps]";
Pattern pattern = Pattern.compile("\\[?(\\w)+\\]?");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.print(matcher.group());
}
Output:
[Caps] [RCaps] C [Caps] [RCaps] atalog [Caps] [RCaps]
Upvotes: 1
Reputation: 7948
instead of split, you could use this pattern to capture what you want
(\[[^][]*\]|[^][]+)
Upvotes: 1
Reputation: 46209
What you need to do is to split both before a [
character and after a ]
character, This translates into the regex (?=\\[)|(?<=\\])
.
Example:
String string = "[Caps][RCaps]C[Caps][RCaps]atalog[Caps][RCaps]";
String[] result = string.split("(?=\\[)|(?<=\\])");
System.out.println(Arrays.toString(result));
This prints:
[[Caps], [RCaps], C, [Caps], [RCaps], atalog, [Caps], [RCaps]]
Upvotes: 3