如何在阅读时在Java中界定"="和"=="

Cod*_*mon 3 java regex

我希望能够输出"=="和"="作为标记.

例如,输入文本文件是:

biscuit==cookie apple=fruit+-()
Run Code Online (Sandbox Code Playgroud)

输出:

biscuit
=
=
cookie
apple
=
fruit
+
-
(
)
Run Code Online (Sandbox Code Playgroud)

我希望输出是什么:

biscuit
==
cookie
apple
=
fruit
+
-
(
)
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

    Scanner s = null;
    try {
        s = new Scanner(new BufferedReader(new FileReader("input.txt")));
        s.useDelimiter("\\s|(?<=\\p{Punct})|(?=\\p{Punct})");

        while (s.hasNext()) {

            String next = s.next();
            System.out.println(next);
       }
    } finally {
        if (s != null) {
            s.close();
        }
    }
Run Code Online (Sandbox Code Playgroud)

谢谢.

编辑:我希望能够保持当前的正则表达式.

Avi*_*Raj 5

只需根据下面的正则表达式分割输入字符串.

String s = "biscuit==cookie apple=fruit"; 
String[] tok = s.split("\\s+|\\b(?==+)|(?<==)(?!=)");
System.out.println(Arrays.toString(tok));
Run Code Online (Sandbox Code Playgroud)

输出:

[biscuit, ==, cookie, apple, =, fruit]
Run Code Online (Sandbox Code Playgroud)

说明:

  • \\s+ 匹配一个或多个空格字符.
  • | 要么
  • \\b(?==+)仅当字符边界后跟=符号时才匹配字边界.
  • | 要么
  • (?<==)寻找=符号.
  • (?!=)并且只有在没有=符号的情况下才匹配边界.

更新:

String s = "biscuit==cookie apple=fruit+-()"; 
String[] tok = s.split("\\s+|(?<!=)(?==+)|(?<==)(?!=)|(?=[+()-])");
System.out.println(Arrays.toString(tok));
Run Code Online (Sandbox Code Playgroud)

输出:

[biscuit, ==, cookie, apple, =, fruit, +, -, (, )]
Run Code Online (Sandbox Code Playgroud)