鉴于您有这一行:
XLOC_000001 XLOC_000001 TC012951 ChLG10:20399-27664 naive BttO NOTEST 0 0.0498691 1.79769e+308 1.79769e+308 0.210754 1 no
你想要1
(倒数第二个元素)
你可以使用这个表达式:
String s ="XLOC_000001 XLOC_000001 TC012951\tChLG10:20399-27664\tnaive\tBttO\tNOTEST\t0\t0.0498691\t1.79769e+308\t1.79769e+308\t0.210754\t1\tno";
Matcher m = Pattern.compile("(?:\t|^)([^\t]*?)\t[^\t]*?(?:\\n|$)").matcher(s);
if(m.find())
System.out.println(m.group(1));
或者,包装在一个函数中:
private static final Pattern pattern = Pattern.compile("(?:\t|^)([^\t]*?)\t[^\t]*?(?:\\n|$)");
public static final String getPenultimateElement(String line) {
Matcher m = pattern.matcher(line);
if(m.find())
return m.group(1)
return null; // or throw exception.
}
或者,调用者可以指定分隔符:
public static final String getPenultimateElement(String line, String separator) {
separator = Pattern.quote(separator);
Matcher m = Pattern.compile("(?:" separator + "|^)([^" + separator + "]*?)" + separator + "[^" + separator + "]*?(?:\\n|$)").matcher(line);
if(m.find())
return m.group(1)
return null; // or throw exception.
}