2

Going by the suggestion provided here I tried using \\W as a delimiter for non word character in string.split function of java.

String str = "id-INT, name-STRING,";

This looks like a really simple string. I wanted to extract just the words from this string. The length of the array that I get is 5 whereas it should be 4. There is an empty string at position right after INT. I don't understand why the space in there is not being considered as non word

Community
  • 1
  • 1
user3527975
  • 1,683
  • 8
  • 25
  • 43

1 Answers1

8

The , and the space are been treated as separate entities, try using \\W+ instead

    String str = "id-INT, name-STRING,";
    String[] parts = str.split("\\W+");
    System.out.println(parts.length);
    System.out.println(Arrays.toString(parts));

Which outputs

4
[id, INT, name, STRING]
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I tried googling the significance of + sign here. Didn't get any. Could you please explain what did the + sign do? BTW : Thank you very much – user3527975 Mar 02 '15 at 03:59
  • From my (puny) understanding, it's grouping all the entities together, so rather than using the individual elements, it's group all the matches that occur simultaneously (`", "`) together into a single match – MadProgrammer Mar 02 '15 at 04:08