Search code examples
javaregexjava.util.scanner

Java Scanner question


How do you set the delimiter for a scanner to either ; or new line?

I tried: Scanner.useDelimiter(Pattern.compile("(\n)|;")); But it doesn't work.


Solution

  • As a general rule, in patterns, you need to double the \.

    So, try

    Scanner.useDelimiter(Pattern.compile("(\\n)|;"));
    

    or

    Scanner.useDelimiter(Pattern.compile("[\\n;]"));
    

    Edit: If \r\n is the problem, you might want to try this:

    Scanner.useDelimiter(Pattern.compile("[\\r\\n;]+"));
    

    which matches one or more of \r, \n, and ;.

    Note: I haven't tried these.