我目前正在开发一个从 csv 文件获取输入的程序。 该输入的结构是众所周知的。我想使用正则表达式读取文件。虽然我知道正则表达式,但我很少使用它们,我想我犯了一些简单的错误......
我为您创建了一个代码 stub 。
前两行是我的“真实”演示输入和相应的正则表达式,它不起作用。每行由一个 ID、一个名称、一个 boolean 属性(1 或 0)和对父节点的引用组成。
下面是我的“训练”演示输入和正则表达式。我去掉了除了 id 之外的所有内容。
扫描仪永远不会匹配我的LINEPATTERN
。我想获取组值也会出现问题......
感谢任何帮助
// private final static String DEMOINPUT = "0,ROOT,1,null\n1,NODE1,1,0\n2,NODE2,0,0";
// private final static String LINEREGEX = "(?<id>\\d+),(?<name>\\w+),(?<active>[01]),(?<predecessor>[\\d+|(null)])";
private final static String DEMOINPUT = "0\n1\n2";
private final static String LINEREGEX = "(?<id>\\d+)";
private final static Pattern LINEPATTERN = Pattern.compile(LINEREGEX);
private ElementComponent root = null;
private String input;
public StringInputTransformer() {
input = DEMOINPUT;
map();
}
private void map() {
try (Scanner sc = new Scanner(input)) {
sc.useDelimiter(",\\n");
while (sc.hasNext(LINEPATTERN)) {
String nextLine = sc.next(LINEREGEX);
Matcher matcher = LINEPATTERN.matcher(nextLine);
int id = Integer.parseInt(matcher.group("id"));
String name = matcher.group("name");
String activeString = matcher.group("active");
String preId = matcher.group("predecessor");
Boolean active = "1".equals(activeString) ? true : false;
ElementComponent element = new ElementComponent(id, name, active);
if ("null".equals(preId)) {
this.root = element;
} else {
handleNonRoot(element);
}
}
}
}
最佳答案
[\d+|(null)] 没有做你认为它会做的事情
你就快到了。这是您需要的正则表达式:
(?<id>\d+),(?<name>\w+),(?<active>[01]),(?<predecessor>\d+|null)
在 the regex demo ,查看右侧 Pane 中的组捕获。
说明
- 主要区别在于最后一组:
(?<predecessor>\d+|null)
你和
[\d+|(null)]
有什么关系?是一种字符类,与一个数字字符或以下字符之一匹配:|
,(
,n
,u
,l
或)
相比之下,
\d+|null
匹配数字或字符串null
,这就是你的意图
要遍历组,您可以执行以下操作:
Pattern regex = Pattern.compile("(?<id>\\d+),(?<name>\\w+),(?<active>[01]),(?<predecessor>\\d+|null)");
Matcher regexMatcher = regex.matcher(yourString);
while (regexMatcher.find()) {
// do something with regexMatcher.group("id")
// do something with regexMatcher.group("name")
// do something with regexMatcher.group("active")
// do something with regexMatcher.group("predecessor")
}
关于java - 如何在java中使用命名组读取csv输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24838842/