URL,扫描仪和分隔符:此Java代码行如何工作?

Nuh*_*man 5 java url delimiter java.util.scanner

任何人都可以帮助我理解这行代码是如何工作的:

String s = new Scanner(new URL("http://example.com").openStream(), "UTF-8").useDelimiter("\\A").next();
Run Code Online (Sandbox Code Playgroud)

该代码用于直接从网页上读取.扫描程序对象到底是如何转换为字符串的,以及为什么我们使用分隔符.

谢谢.

Kuz*_*eko 9

以下是滥用缩进的情况

     new Scanner(                           // A new scanner is created
             new URL("http://example.com")  // the scanner takes a Stream 
                                            // which is obtained from a URL
          .openStream(),                    // - openStream returns the stream
       "UTF-8")                             // Now the scanner can parse the        
                                            // stream character by character
                                            // with UTF-8 encoding

     .useDelimiter("\\A")                   // Now the scanner set as 
                                            // delimiter the [Regexp for \A][1]
                                            // \A stands for :start of a string!

   .next();                                 // Here it returns the first(next) 
                                            // token that is before another
                                            // start of string. 
                                            // Which, I'm not sure 
                                            // what it will be
Run Code Online (Sandbox Code Playgroud)

来自Java文档

一个简单的文本扫描程序,可以使用正则表达式解析基本类型和字符串.扫描程序使用分隔符模式将其输入分解为标记,分隔符模式默认匹配空格.然后可以使用各种下一种方法将得到的标记转换成不同类型的值.

所以你只需将其替换\A为分隔符(而不是空格).但\A 在评估正则表达式时有一个特定的含义!

如果您的流仅包含以下文本

\ Ahello世界!\再见!\ A

您的代码将返回整行 \Ahello world!\A Goodbye!\A

如果你想删除反斜杠的序列,然后是大写的A,那么你应该使用\\\\A.

感谢@Faux Pas指出这一点!