简体   繁体   English

Java 中的正则表达式捕获,如 C#

[英]Regex Captures in Java like in C#

I have a to rewrite a part of an existing C#/.NET program using Java.我必须使用 Java 重写现有 C#/.NET 程序的一部分。 I'm not that fluent in Java and am missing something handling regular expressions and just wanted to know if I'm missing something or if Java just doesn't provide such feature.我对 Java 不是很流利,并且缺少处理正则表达式的内容,只是想知道我是否缺少某些内容,或者 Java 是否不提供此类功能。

I have data like我有类似的数据

2011:06:05 15:50\t0.478\t0.209\t0.211\t0.211\t0.205\t-0.462\t0.203\t0.202\t0.212

The Regex pattern I'm using looks like:我正在使用的正则表达式模式如下所示:

?(\d{4}:\d{2}:\d{2} \d{2}:\d{2}[:\d{2}]?)\t((-?\d*(\.\d*)?)\t?){1,16}

In .NET I can access the values after matching using match.Group[3].Captures[i] .在 .NET 中,我可以使用match.Group[3].Captures[i]访问匹配后的值。

In Java I haven't found anything like that.在 Java 中我没有找到类似的东西。 matcher.group(3) just returns an empty string. matcher.group(3)只返回一个空字符串。

How can I achieve a behaviour like the one I'm used to from C#?如何从 C# 实现像我习惯的行为?

As I mentioned in the comments, Java will only return the last value of a multiple valued group fit.正如我在评论中提到的,Java 只会返回多值组拟合的最后一个值。 So you should first use regex to isolate the last part of your string with the values:因此,您应该首先使用正则表达式将字符串的最后一部分与值隔离:

strg = "0.478\t0.209\t0.211\t0.211\t0.205\t-0.462\t0.203\t0.202\t0.212"

and then just split around the tabs:然后围绕标签拆分:

String[] values = strg.split("\\t");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM