gpt4 book ai didi

java - URL、扫描器和分隔符 : How does this Java Line of Code Works?

转载 作者:搜寻专家 更新时间:2023-10-31 08:25:31 25 4
gpt4 key购买 nike

谁能帮我理解这行代码是如何工作的:

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

该代码用于直接从网页读取。扫描器对象究竟是如何转换为字符串的,以及我们为什么使用定界符。

谢谢。

最佳答案

这是发生的事情,滥用缩进

     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

From the Java documentation

A simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

所以您只是将 \A 替换为分隔符(而不是空格)。但是 \A has a specific meaning when evaluating as regular expression!

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

\Ahello world!\A Goodbye!\A

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

如果您想去除反斜杠后跟大写字母 A 的序列,那么您应该使用 \\\\A

感谢@Faux Pas 指出这一点!

关于java - URL、扫描器和分隔符 : How does this Java Line of Code Works?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36278304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com