0

我正在对 findInLine 对象进行测试,但它不起作用,我不知道为什么。这是代码:

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

这是output: 9)

如果我想让变量a得到我这样写的所有字符串,我需要做什么:a = (9,9)而不是a = 9)

4

2 回答 2

0

您需要在正则表达式中转义括号。现在正则表达式匹配逗号。

此外,您应该意识到Scanner.findInLine()输入也有所进步。

尝试

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

来验证这一点。

于 2013-03-20T21:40:05.087 回答
0

什么我都明白。您想输入一些字符串,如果该字符串与您的模式匹配,则需要将其显示在控制台中。这将为您提供正确的输出。

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 正则表达式教程

扫描仪 findInLine()

输入:

(9,9)

输出 :

(9,9)
于 2013-03-20T21:58:31.357 回答