来自格式化文件的 Java 输入
我正在尝试从具有各种不同行的文件中获取输入。
例如,格式为书名,作者:借阅人第二名名字:借阅人状态
这里有一些示例行。
The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10
Crime And Punishment, Fyodor Dostoyevsky
The Clan Of The Cave Bear, Jean M Auel
The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10
因此,我在设置扫描仪后尝试使用 useDelimiter,但由于有些行较短,我不知道该怎么做。
I'm trying to getting input from a file which has various different lines.
e.g. the format is Book title, Author:Borrower second name First Name:Borrower state
here's some example lines.
The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10
Crime And Punishment, Fyodor Dostoyevsky
The Clan Of The Cave Bear, Jean M Auel
The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10
So I tried to use useDelimiter after setting up a scanner, but since some line are shorter I don't no quite what to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个基于正则表达式的解决方案:
给定您的示例输入,它会打印:
Here is a solution based on regular expressions:
Given your sample input, it prints:
逐行读取文件,使用
[^,:]
正则表达式匹配每行中的数据(顺序find
将带来标题、作者、借阅者、状态、如果有的话)。Read the file line by line, use the
[^,:]
regular expression to match data in each line (sequentialfind
will bring title, author, and borrower, state, if any).你可以使用 .split()
You could use .split()
为什么总是建议对于如此琐碎的任务使用正则表达式之类的超大工具?为什么不简单地使用旧的
line.indexOf()
或line.lastIndexOf()
方法呢?Why always for such trivial tasks such oversized tools like regular expressions are suggested? Why not simply use the good old
line.indexOf()
orline.lastIndexOf()
methods?我将分割每一行(使用 String.split),并传入冒号作为分隔符。然后对 split 返回的第一个元素使用 lastIndexOf(',') ,以便将作者与书籍分开:
I would split each line (using String.split) passing in the colon as the delimiter. Then use lastIndexOf(',') on the first element returned by split in order to separate the author from the book: