Question

For example, input will be like:

AddItem rt456 4  12 BOOK “File Structures” “Addison-Wesley” “Michael Folk”

and I want to read all by using scanner and put it in a array.

like:

   info[0] = rt456
   info[1] = 4
   ..
   ..
   info[4] = File Structures
   info[5] = Addison-Wesley

So how can I get the string between quotes?

EDIT: a part of my code->

public static void main(String[] args) {
            String command;
        String[] line = new String[6];
        Scanner read = new Scanner(System.in);
        Library library = new Library();

        command = read.next();

        if(command.matches("AddItem"))
        {
            line[0] = read.next(); // Serial Number
            line[1] = read.next(); // Shelf Number
            line[2] = read.next(); // Shelf Index
            command = read.next(); // Type of the item. "Book" - "CD" - "Magazine"

            if(command.matches("BOOK"))
            {
                line[3] = read.next(); // Name
                line[4] = read.next(); // Publisher
                line[5] = read.next(); // Author

                Book yeni = new Book(line[0],Integer.parseInt(line[1]),Integer.parseInt(line[2]),line[3],line[4],line[5]);


    }
    }
}

so I use read.next to read String without quotes.

SOLVED BY USING REGEX AS

read.next("([^\"]\\S*|\".+?\")\\s*");
Was it helpful?

Solution 3

An alternative using a messy regular expression:

public static void main(String[] args) throws Exception {
    Pattern p = Pattern.compile("^(\\w*)[\\s]+(\\w*)[\\s]+(\\w*)[\\s]+(\\w*)[\\s]+(\\w*)[\\s]+[“](.*)[”][\\s]+[“](.*)[”][\\s]+[“](.*)[”]");
    Matcher m = p.matcher("AddItem rt456 4  12 BOOK “File Structures” “Addison-Wesley” “Michael Folk”");

    if (m.find()) {
        for (int i=1;i<=m.groupCount();i++) {
            System.out.println(m.group(i));
        }
    }
}

That prints:

AddItem
rt456
4
12
BOOK
File Structures
Addison-Wesley
Michael Folk

I assumed quotes are as you typed them in the question “” and not "", so they dont need to be escaped.

OTHER TIPS

You can use StreamTokenizer for this in a pinch. If operating on a String, wrap it with a StringReader. If operating on a file just pass your Reader to it.

// Replace “ and ” with " to make parsing easier; do this only if you truly are
// using pretty quotes (as you are in your post).
inputString = inputString.replaceAll("[“”]", "\"");

StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(inputString));
tokenizer.resetSyntax();
tokenizer.whitespaceChars(0, 32);
tokenizer.wordChars(33, 255);
tokenizer.quoteChar('\"');

while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
    // tokenizer.sval will contain the token
    System.out.println(tokenizer.sval);
}

You will have to use an appropriate configuration for non-ASCII text, the above is just an example.

If you want to pull numbers out separately, then the default StreamTokenizer configuration is fine, although it uses double and provides no int numeric tokens. Annoyingly, it is not possible to simply disable number parsing without resetting the syntax from scratch.

If you don't want to mess with all this, you could also consider changing the input format to something more convenient, as in Steve Sarcinella's good suggestion, if it is appropriate.

As a reference, take a look at this: Scanner Docs

How you read from the scanner is determined by how you will present the data to your user.

If they are typing it all on one line:

Scanner scanner = new Scanner(System.in);
String result = "";
System.out.println("Enter Data:");
result = scanner.nextLine();

Otherwise if you split it up into input fields you could do:

Scanner scanner = new Scanner(System.in);
System.out.println("Enter Identifier:");
info[0] = scanner.nextLine();
System.out.println("Enter Num:");
info[1] = scanner.nextLine();
...

If you want to validate anything before assigning the data to a variable, try using scanner.next(""); where the quotes contain a regex pattern to match

EDIT:

Check here for regex info.

As an example, say I have a string

String foo = "The cat in the hat";

regex (Regular Expressions) can be used to manipulate this string in a very quick and efficient manner. If I take that string and do foo = foo.replace("\\s+", "");, this will replace any whitespace with nothing, therefore eliminating whitespace.

Breaking down the argument \\s+, we have \s which means match any character that is whitespace.

The extra \ before \s is a an escape character that allows the \s to be read properly.

The + means match the previous expression 0 or more times. (Match all).

So foo, after running replace, would be "TheCatInTheHat"

Same this regex logic can apply to scanner.next(String regex);

Hopefully this helps a bit more, I'm not the best at explanation :)

You can try this. I have prepared the demo for your requirement

  public static void main(String args[]) {
      String str = "\"ABC DEF\"";
      System.out.println(str);
      String str1 =  str.replaceAll("\"", "");
      System.out.println(str1);
  }

After reading just replace the double quotes with empty string

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top