Java Scanner question

Razvi picture Razvi · Dec 30, 2009 · Viewed 18.3k times · Source

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.

Answer

Powerlord picture Powerlord · Dec 30, 2009

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.