问题
How do I use the useDelimiter()
method of the Scanner
class to use both the comma (,) and the new line character (\n) as delimiters?
I am parsing some text from a csv file.
回答1:
Scanner s = new Scanner("hello, world \n hello world");
s.useDelimiter(",|\\n");
while(s.hasNext()){
System.out.println(s.next());
}
Output
hello
world
hello world
- JavaDoc
回答2:
How about useDelimiter(",|\\n");
回答3:
useDelimiter takes a regex pattern, so, it would be something like ",|\n"
回答4:
Jigar is absolutely correct.
But if it doesn't work, try ",|\\r"
since most text files have \r\n instead of just \n
回答5:
Using Scan Delimiters for Excel files - don't overlook the RegEx thing. In my case the excel file is delimitedby '|'. I have been spending significant time to parse rows using scanner.useDelimiter("|"), and got back character by character. Replacing that with scanner.useDelimiter("\\|") has solved my issue!
来源:https://stackoverflow.com/questions/4898263/multiple-delimiters-in-scanner-class-of-java