-2

I wish to use Scanner class method : .useDilimiter() to parse a file, previously I would've used a series of .replaceAll() statements to replace what I wanted the dilimiter to be with white space.

Anyway, I'm trying to make a Scanner's dilimiter the any of the following characters: ., (,),{,},[,],,,! and standard white space. How would I go about doing this?

nits.kk
  • 4,781
  • 4
  • 24
  • 48
Quabs
  • 51
  • 6
  • 1
    Possible duplicate of [Java - Using multiple delimiters in a scanner](http://stackoverflow.com/questions/6244670/java-using-multiple-delimiters-in-a-scanner) – Joe C Apr 23 '17 at 22:44

1 Answers1

0

Scanner uses regular expression (regex) to describe delimiter. By default it is \p{javaWhitespace}+ which represents one or more (due to + operator) whitespaces.

In regex to represent single character from set of characters we can use character class [...]. But since [ and ] in regex represents start and end of character class these characters are metacharacters (even inside character class). To treat them as literals we need to escape them first. We can do it by

  • adding \ (in string written as "\\") before them,
  • or by placing them in \Q...\E which represents quote section (where all characters are considered as literals, not metacharacters).

So regex representing one of ( ) { } [ ] , ! characters can look like "[\\Q(){}[],!\\E]".

If you want to add support for standard delimiter you can combine this regex with \p{javaWhitespace}+ using OR operator which is |.

So your code can look like:

yourScanner.useDelimiter("[\\Q(){}[],!\\E]|\\p{javaWhitespace}+");
Pshemo
  • 113,402
  • 22
  • 170
  • 242
  • Thank you! Very helpful as I'm still pretty confused with regex – Quabs Apr 23 '17 at 23:55
  • @Quabs You are welcome. Since you are new here you may not know that if some answer solves your problem you can mark it as solution. More info at ["How does accepting an answer work?"](http://meta.stackexchange.com/a/5235). – Pshemo Apr 25 '17 at 00:21