-3

"John","100.00","200.00"

How to read the content of text file and then print string under quotes.

The output should be Jhon 100.00 200.00

String CUSTOMER, CURRENT, NEW;
    Scanner sc = new Scanner(str);
    sc.useDelimiter(",");
    while(sc.hasNext()){
        CUSTOMER = sc.next();
        CURRENT = sc.next();
        NEW = sc.next();
           System.out.println("" + CUSTOMER + " " + CURRENT + 
             " " + NEW);  
          }
          sc.close();

How to separate the tokens from quotes. output for above code which I am getting is this "Jhon" "100.00" "200.00"

3 Answers3

0

You can get the required output with following :

public static void main(String[] args) {
    Pattern p = Pattern.compile(".*?\\\"(.*?)\\\".*?");
    Matcher m = p.matcher("\"John\",\"100.00\",\"200.00\"");

    while (m.find()) {
        System.out.println(m.group(1));
    }
}

Explain

.*?   - anything
\\\" - quote (escaped)
(.*?) - anything (captured)
\\\" - another quote
.*?  - anything

Output

John
100.00
200.00
Madushan Perera
  • 2,568
  • 2
  • 17
  • 36
0

https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

The scanner can also use delimiters other than whitespace. This example reads several items in from a string:

 String input = "1 fish 2 fish red fish blue fish";
 Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");

So you can avoid first and last quote by substring(1,len-1) and useDelimiter(\",\") with 3-symbols delim in inner part.

    String str = "\"John\",\"100.00\",\"200.00\"";
    System.out.println(str);
    String CUSTOMER, CURRENT, NEW;
    Scanner sc = new Scanner(
        str.substring(1,str.length()-1)  // <--- here substring 
    );
    sc.useDelimiter("\",\""); // <---- here your split: <token>","<token>

    while(sc.hasNext()){
        CUSTOMER = sc.next();
        CURRENT = sc.next();
        NEW = sc.next();
        System.out.println("" + CUSTOMER + " " + CURRENT + " " + NEW);  
    }
    sc.close();
Serge Breusov
  • 1,316
  • 4
  • 11
  • 24
0

Here is another way to accomplish the task:

String line, customerName, currentVal, newVal;
try (Scanner sc = new Scanner(new File("salesrep.txt"))) {
    while (sc.hasNextLine()) {
        line = sc.nextLine().replace("\"", "");
        //skip blank lines (if any)
        if (line.equals("")) {
            continue;
        }
        String[] lineData = line.split(",");
        customerName = lineData[0];
        currentVal = lineData[1]; // or:  double currentVal = Double.parseDouble(lineData[1]);
        newVal = lineData[2];     // or:  double newVal = Double.parseDouble(lineData[2]);
        System.out.println("" + customerName + " " + currentVal + " " + newVal);
    }
}
catch (FileNotFoundException ex) {
    ex.printStackTrace();
}
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22