Java扫描器头痛

编程入门 行业动态 更新时间:2024-10-25 13:14:27
本文介绍了Java扫描器头痛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个文本文件,如下所示:

I have a text file which looks like:

name1 1 0 1 0 1 0 1 1 1 0 0 0 0 0 0 name2 1 0 1 0 1 0 0 1 1 0 0 0 0 0 1

即纯文本标签,后跟几行,其中1/0以空格分隔。 1/0的行数是可变的,但任何两个特定标签之间的每一行都应具有相同的1/0数(尽管可能不会)。

i.e., a plaintext label followed by a few rows with 1/0 separated by spaces. The number of rows of 1/0 is variable, but each row between any two particular labels should have the same number of 1/0s (though might potentially not).

如何使用扫描仪抓取每个名称+行块?有什么优雅的方法可以强制行数的一致性(如果不一致,还可以提供某种反馈)?

How do I grab each name+rows chunk with a scanner? Is there any elegant way to enforce the consistency on the number of rows (and provide some sort of feedback if they aren't consistent)?

我在想是使用巧妙的定界符规范的便捷方法,但我似乎无法正常工作。

I'm thinking there might be a convenient way with clever delimiter specification, but I can't seem to get that working.

推荐答案

对另一个问题的有用答案(感谢 Bart ):

static final String labelRegex="^\\s*\\w+$"; static final Pattern labelPattern = Patternpile(labelRegex, Pattern.MULTILINE); Matcher labelMatcher = labelPattern.matcher(""); static final String stateRegex = "([10] )+[10]\\s+"; static final String statesRegex = "("+stateRegex+")+"; static final Pattern statesPattern = Patternpile(statesRegex, Pattern.MULTILINE); Matcher stateMatcher = statesPattern.matcher(""); static final String chunkRegex = "(?="+labelRegex+")"; static final Pattern chunkPattern = Patternpile(chunkRegex,Pattern.MULTILINE); Scanner chunkScan; public void setSource(File source) { if(source!=null && source.canRead()) { try { chunkScan = new Scanner(new BufferedReader(new FileReader(source))); chunkScan.useDelimiter(chunkPattern); } catch (IOException e) { e.printStackTrace(); } } } public Map<String, List<GraphState>> next(int n) { Map<String,List<GraphState>> result = new LinkedHashMap<String,List<GraphState>>(n); String chunk, rows; int i=0; while (chunkScan.hasNext()&&i++<n) { chunk = chunkScan.next().trim(); labelMatcher.reset(chunk); stateMatcher.reset(chunk); if (labelMatcher.find()&&stateMatcher.find()) { rows = stateMatcher.group().replace(" ", ""); result.put(labelMatcher.group(), rowsToList(rows.split("\\n"))); } } return result; }

更多推荐

Java扫描器头痛

本文发布于:2023-08-07 06:48:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1317581.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:扫描器   头痛   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!