separating each word in a string even if they are not separated by spaces

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Norgy
    New Member
    • May 2013
    • 56

    separating each word in a string even if they are not separated by spaces

    if we have this string : number of doses(1000mg/m2)
    and i want to separate each word in a string
    when i do this
    Code:
            String doses = "number of doses(1000mg/m2)";
            String[] split = doses.split(" ");
            for(int i=0 ; i<split.length ; i++){
                System.out.println(split[i]);
            }
    the output is :
    number
    of
    doses(1000mg/m2)
    but i want to separate each word so that the output is:
    number
    of
    doses
    (
    1000
    mg/m2
    )

    how can i do this??
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    Use a regular expression. It should match Whitespace-characters (so they get deleted in the result array) and word (or number) delimiters. Word delimiters are positions and no characters, so no character gets deleted inside the splitted array. You can match positions with regEx "lookahead" and "lookbehind "

    This regex give you the wanted result:
    Code:
    String doses = "number   of doses(1000mg/m2)";
    String regEx = "\\s+|(?=[\\(\\)])|(?<=[\\(\\)])|(?=(?<=\\d)\\D)";
    String[] results = doses.split(regEx);
    System.out.println("array:" + Arrays.asList(results));
    gives:
    array:[number, of, doses, (, 1000, mg/m2, )]

    Comment

    Working...