简体   繁体   English

如何使用正则表达式提取字符串的一部分

[英]how to extract a part of string using regex

Am trying to extract last three strings ie 05,06,07. 我试图提取最后三个字符串,即05,06,07。 However my regex is working the other way around which is extracting the first three strings. 但是我的正则表达式正以另一种方式工作,即提取前三个字符串。 Can someone please help me rectify my mistake in the code. 有人可以帮我纠正代码中的错误吗?

Pattern p = Pattern.compile("^((?:[^,]+,){2}(?:[^,]+)).+$");
String line = "CgIn,f,CgIn.util:srv2,1,11.65,42,42,42,42,04,05,06,07";
Matcher m = p.matcher(line);
String result;
if (m.matches()) {
    result = m.group(1);
}
System.out.println(result);

My current output: 我当前的输出:

CgIn,f,CgIn.util:srv2

Expected output: 预期产量:

05,06,07

You may fix it as 您可以将其修复为

Pattern p = Pattern.compile("[^,]*(?:,[^,]*){2}$");
String line = "CgIn,f,CgIn.util:srv2,1,11.65,42,42,42,42,04,05,06,07";
Matcher m = p.matcher(line);
String result = "";
if (m.find()) {
    result = m.group(0);
}
System.out.println(result);

See the Java demo 参见Java演示

The regex is 正则表达式是

[^,]*(?:,[^,]*){2}$

See the regex demo . 参见regex演示

Pattern details 图案细节

  • [^,]* - 0+ chars other than , [^,]* -除+以外的0个字符,
  • (?:,[^,]*){2} - 2 repetitions of (?:,[^,]*){2} -重复2次
    • , - a comma , -逗号
    • [^,]* - 0+ chars other than , [^,]* -除+以外的0个字符,
  • $ - end of string. $ -字符串结尾。

Note that you should use Matcher#find() with this regex to find a partial match. 请注意,您应将此Matcher#find()与此正则表达式一起使用以查找部分匹配项。

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

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