Java Scanner Delimiter Usage

自古美人都是妖i 提交于 2019-12-02 10:15:48

You can use a positive look ahead in your regex. Look aheads (and behinds) are not included in the match, so they won't be "eaten" by the Scanner. This regex will probably do what you want:

(?=text/numbers)

The delimiter will be the empty String right before the sub-string text/numbers.

Here's a small demo:

public class Main {
    public static void main(String[] args) {
        String text = "text/numbers mix\n"+
                "numbers\n"+
                "numbers\n"+
                "text/numbers mix\n"+
                "numbers\n"+
                "numbers\n"+
                "numbers";
        String regex = "(?=text/numbers)";
        Scanner scan = new Scanner(text).useDelimiter(regex);
        while(scan.hasNext()) {
            System.out.println("------------------------");
            System.out.println(">"+scan.next().trim()+"<");
        }
    }
}

which produces:

------------------------
>text/numbers mix
numbers
numbers<
------------------------
>text/numbers mix
numbers
numbers
numbers<
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!