codenaugh
codenaugh

Reputation: 857

Java split and throw away on repeated char using regex

I'm really struggling with regex right now...

I've read up and looked at a lot of examples, but cannot seem to find the answer. I'd like to split a string when the string "::" is found, and I would like to discard those two characters. The closest I have gotten was splitting on the correct pattern, but it kept the colons. Here is an example of my input and desired output:

String input = "One::Two::Three";

I would like the output to be:

output[0]: "One"
output[1]: "Two"
output[2]: "Three"

Upvotes: 0

Views: 398

Answers (2)

bystander
bystander

Reputation: 549

String input = "One::Two::Three";
String[] output = input.split("::");
for(int i = 0; i < output.length; i++) {  
    System.out.println(output[i]);  
}  

Upvotes: 5

Michael Ho Chum
Michael Ho Chum

Reputation: 939

You can use the String#split() method which takes a separator string as argument and outputs the divided string to an array. Note that the argument can be a regular expression.

String input = "One::Two::Three";
String[] output = input.split("::");

System.out.println(output[0]); // One
System.out.println(output[1]); // Two
System.out.println(output[2]); // Three  

Here's the official documentation for String#split()

Upvotes: 5

Related Questions