如何从Java的扫描仪中获取匹配的分隔符?

时间:2016-12-02 02:19:14

标签: java regex java.util.scanner

使用以下代码作为示例(从docs修改):

 String input = "1 fish 2 fish red sheep blue sheep";
 Scanner s = new Scanner(input).useDelimiter("\\s*(fish|sheep)\\s*");
 System.out.println(s.nextInt());
 System.out.println(s.nextInt());
 System.out.println(s.next());
 System.out.println(s.next());
 s.close(); 

有没有办法弄清楚它是sheep还是fish

3 个答案:

答案 0 :(得分:1)

请改用此代码:

String input = "1 fish 2 fish red sheep blue sheep";
Pattern pattern = Pattern.compile("\\s*(fish|sheep)\\s*");
Matcher matcher = pattern.matcher(input)

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

在此代码中,matcher.group(1)返回正则表达式中组1匹配的值,在本例中为(fish|sheep)。您可以通过括号括起来创建组。您还可以获得返回整个匹配的组0。

答案 1 :(得分:0)

回答了我自己的问题 - 这可以通过不指定分隔符并使用next(Pattern)代替来完成:

String input = "1 fish 2 fish red sheep blue sheep";
Pattern animal = Pattern.compile("\\s*(fish|sheep)\\s*");
Scanner sc = new Scanner(input);

while (sc.hasNext()) {
    System.out.println(sc.next());
    System.out.println(sc.next(animal));
}

输出:

1
fish
2 
fish 
red 
sheep 
blue 
sheep

修改 我的方法是错误的 - 这只是因为分隔符是空格(在我的实际场景中不是这种情况)。这是一种更好的方法:

String input = "1.fish.2.fish.red.sheep.blue.sheep";
Pattern animal = Pattern.compile("\\.*(fish|sheep)\\.*");
Scanner sc = new Scanner(input);

int endOfLastMatch = 0;
while (sc.hasNext()) {
    sc.useDelimiter(animal);
    String nextMatch = sc.next();

    int startOfCurrentMatch = sc.match().start(0);
    if (endOfLastMatch > 0) {
        System.out.println(new String(input.getBytes(), endOfLastMatch, startOfCurrentMatch - endOfLastMatch)); 
    }

    System.out.println(nextMatch);
    endOfLastMatch = sc.match().end();
}

if (endOfLastMatch < input.length()) {
    System.out.println(new String(input.getBytes(), endOfLastMatch, input.length() - endOfLastMatch));  
}

输出:

1
.fish.
2
.fish.
red
.sheep.
blue
.sheep

答案 2 :(得分:0)

可能您正在寻找Scanner.findInLine()方法

    String input = "1 fish 2 fish red sheep blue sheep";
    Pattern delim = Pattern.compile("\\s*(fish|sheep)\\s*");
    Scanner s = new Scanner(input).useDelimiter(delim);
    while (s.hasNext()) {
        System.out.println(s.next());
        System.out.println(s.findInLine(delim));
    }
    s.close();