简体   繁体   中英

find in line java object , how to scan all the input?

im doing a test about findInLine object but its not working and i dont know why. this is the code:

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.print("enter string: ");
    String a = null;
    String pattern ="(,)";

    if (input.findInLine(pattern) != null){

        a = input.nextLine();

    }
    System.out.println(a);

enter string: (9,9) <---------- that is what i wrote

this is the output: 9)

what i need to do if i want that the variable a will get all the string that i wrote like this: a = (9,9) and not a = 9)

You need to escape your brackets in the regex. Now the regex matches the comma.

Moreover, you should realize that Scanner.findInLine() also advances on the input.

Try

String pattern = "\\([0-9]*,[0-9]*\\)";
String found = input.findInLine(pattern);
System.out.println(found);

to verify this.

Whatever I understood. You want to input some string and if that string gets matches to your pattern you need that to be shown in console. This will give you correct output.

import java.util.Scanner;

public class InputScan {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        String a;
        System.out.print("enter string: ");
        String pattern = "\\(\\d+,\\d+\\)"; // Its regex
        // For white spaces as you commented use following regex
        // String pattern = "\\([\\s+]?\\d+[\\s+]?,[\\s+]?\\d+[\\s+]?\\)";
        if ((a = input.findInLine(pattern)) != null){
            System.out.println(a);
        }
    }
}

Java Regex Tutorial

Scanner findInLine()

Input:

(9,9)

Output :

(9,9)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM