2013-02-06 71 views
2

我必須從.txt文件中分離一個值。 我創建了一個LineNumberReader並使用.split(「\ t」)來分隔單詞,但我只需要第二個最後的值(q值)。 有沒有指定.split()的選項?x選項卡後分割字符串

這是我的.txt文件

test_id gene_id gene locus sample_1 sample_2 status value_1 value_2 log2(fold_change) test_stat p_value q_value significant 
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#split(String regex, int limit)方法,要提取並得到你想要的字符串中的一行代碼列後停止分裂:

String line = "A\tB\tC\tD\tE\tF"; // tab separated content 
    int column = 3; // specify the column you want (first is 1) 
    String content = line.split("\t", column + 1)[column - 1]; // get content 
    System.out.println(content); // prints C (3rd column) 
+0

謝謝,作品剛剛完美。祝你有美好的一天 – Mirar

1
String[] array = someString.split("\t"); 
String secondToLast = array[array.length - 2]; 
+0

這將在_slash t_上分割,而不是在_tab_ – jlordo

+0

感興趣的值總是在相同的陣列位置。爲了得到這個值並不難,但因爲它產生了一堆不需要的字符串。我正在尋找一種方法來減少字符串輸出 – Mirar

+0

@Mirar:看到我的答案。 – jlordo

0

鑑於你有這樣一行:

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. 
}