Java Scanner Delimiter Usage

前端 未结 1 589
孤城傲影
孤城傲影 2020-12-21 19:07

I\'d like to specify a delimiter for a scanner that splits on some pattern, but doesn\'t remove that pattern from the tokens. I can\'t seem to make this work, as anything t

相关标签:
1条回答
  • 2020-12-21 19:23

    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<
    
    0 讨论(0)
提交回复
热议问题