-1

I'm trying to create a basic model viewer for Wavefront Object files, and part of the reading of the file includes splitting each line. The faces are defined based on slashes. These are the different types of faces that can be parsed from Wikipedia:

  f v1 v2 v3 v4 ... <- Face built of vertices
  f v1/vt1 v2/vt2 v3/vt3 ... <- Face built of vertices + textures
  f v1/vt1/vn1 v2/vt2/vn2 v3/vt3/vn3 ... <- Face built of vertices, textures, and normals
  f v1//vn1 v2//vn2 v3//vn3 ... <- Face built of vertices and normals

I've been reading each line progressively, and if it starts with "f ", I send that to another method after removing the first two characters of the entire line to create the face.

e.g. f v1 v2 v3 would go to v1 v2 v3

When I have to deal with lines with slashes in them, I think I'm splitting them wrong as I'm not getting proper results. I'm currently using these two splits:

   string.split("/");
   string.split("//");

Does this create problems because the split parameter is supposed to be a regex while I'm trying to split by characters which are (I believe to be) commonly used in regex?

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
user1625108
  • 91
  • 1
  • 5
  • 3
    `/` is not a special character in Java regex. You're thinking of ``\``. – Matt Ball Jun 16 '13 at 19:28
  • 3
    If you split first by `/` you will mess up the `//` delimiters; you should probably split by `//` *before* you split by `/` (assuming you have both `/` and `//` in the same string to be split). – Matthew Watson Jun 16 '13 at 19:29
  • 2
    `I think I'm splitting them wrong as I'm not getting proper results` could you show your current results and expected results? To edit your question click 'edit' button under your question or here [[edit]]. – Pshemo Jun 16 '13 at 19:30
  • 1
    Splitting on *anything* is unlikely to produce the result you're looking for; you also have spaces in there. You probably want pattern matching with captures. – Brian Roach Jun 16 '13 at 19:36
  • When splitting by a literal and not regex, I'd recommend using [Pattern.quote()](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote%28java.lang.String%29). This way there is no issue if any of the characters in the delimiter string are a special regexp character. – prunge Jun 16 '13 at 20:43

1 Answers1

0

Slash is nothing special in regex. Try this:

for (String facePart : input.replaceAll("^f "), "").split(" ")) {
    String[] data = facePart.split("/");
    String vertex = data[0];
    String texture = data.length > 1 ? data[1] : "";
    String normal = data.length > 2 ? data[2] : "";
    // do something with the info
    // variables will be blank if missing from input
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722