Question

I am trying to write a code that will split a line from a text file on these characters "<" or ">". I have tried spliting with a StringTokenizer with those as delemiters but it still splits on spaces. I have also used line = file.split("(<|>)");

Both split on spaces and i need it not to do that.

Was it helpful?

Solution

Try

  public static void main(String[] args)
  {
    String s = "123 4545>abc5  >4545454 45454 45 44555< 454545";
    String[] tokens = s.split("<|>");
    for(String t : tokens)
      System.out.println(t);
  }

Output:

123 4545
abc5  
4545454 45454 45 44555
 454545

OTHER TIPS

Try

String[] split= file.split("[\\<?\\>?]");

Brackets ([]) denote a choice between characters.

A question mark (?) denotes a cardinality - 0 or 1

I just tried, it works fine.

String x = "afa f<afaf>a fa<af";
for (String s : x.split("<|>")) {
    System.out.println(s);
}

Output:

afa f
afaf
a fa
af

Probably because in your code, you have "(<|>" not "<|>".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top