-1

I have a line in a file.txt, |a|b|c|d|, that I want to extract the values between | (result a,b,c,d) How can I do this?

Alex
  • 763
  • 11
  • 23

3 Answers3

0

From String[] split(String regex)

Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

The string "boo:and:foo", for example, yields the following results with these expressions:

Regex Result
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }

Use following code:

String[] arr = "|a|b|c|d|".split("\\|");
Sumit Singh
  • 24,095
  • 8
  • 74
  • 100
  • 1
    Could you please [edit] your answer to give an explanation of why this code answers the question? Code-only answers are [discouraged](http://meta.stackexchange.com/questions/148272), because they don't teach the solution. – DavidPostill Apr 22 '15 at 10:08
  • @DavidPostill thanks, updated – Sumit Singh Apr 22 '15 at 10:14
0

The pipe (|) is a special character in regular expression language (the split method takes a regular expression as a parameter), and thus needs to be escaped.

You will need to use something like so: String[] str = "|a|b|c|d|".split("\\|");

Given this:

 String[] str = "|a|b|c|d|".split("\\|");
    for(String string : str)
        System.out.println(string);

Will yield:

  //The first string will be empty, since your string starts with a pipe.
a
b
c
d
npinti
  • 51,070
  • 5
  • 71
  • 94
0
public static void main(String[] args) throws IOException {

    FileReader fr = new FileReader(new File(
            "file.txt"));
    BufferedReader br = new BufferedReader(fr);
    String st;
    StringBuffer sb = new StringBuffer();
    st = br.readLine();
    if (st != null) {
        StringTokenizer strTkn = new StringTokenizer(st, "|");
        while (strTkn.hasMoreElements()) {
            sb.append(strTkn.nextElement());
        }
    }

    System.out.println(sb);

}
Alok Pathak
  • 865
  • 1
  • 8
  • 19