سؤال

I need to parse a text file that is Hierarchical with the number of leading spaces determining the depth of the property, and return set of java Objects for each level. I thought about using a scanner or reading each line in individually but that seemed cumbersome. Perhaps regex would be a better solution? The file I need to read looks like:

workarea = workarea:
  size = (1583, 805, 0)
  areas = areas:
    place = array: 2 items
      0 = int: 0
      1 = int: 0
    size = (1583, 805, 0)
    areas = array: 2 items
      0 = object:
        type = myType:
          prop1 = prop1
          prop2 = array: 2 items
            0 = object:
              prop1 = prop1
              prop2 = prop2
            1 = object:
              prop1 = prop1
              prop2 = prop2
        position = (5, 5, 0)
        size = (735, 226, 0)
      1 = object:
        type = myType2:
          prop1 = prop1
          prop2 = array: 2 items
            0 = object:
              prop1 = prop1
              prop2 = prop2
            1 = object:
              prop1 = prop1
              prop2 = prop2
          prop3 = prop3
        position = (5, 5, 0)
        size = (735, 226, 0)

As you can see there is an "area" object defined and then filled 5 lines lower with "objects" of a specific type (myType1 and myType2). Each of these subobjects have different properties,(in the example myType2 has prop3. that may contain arrays of other objects)

What would be the best way to get this structure into a group of Java Objects: eg

Workarea
public String size = "1583,805"
public List<Areas> = (
        {Area
         public String type = "myType"
         Public String prop1 = prop1
         etc....
         },
         {Area
         public String type = "myType2"
         Public String prop1 = prop1
         etc....
         }
)
هل كانت مفيدة؟

المحلول

I ended up building a Parser Class with a couple of methods getValue and getValues (which returned and array of values matching the Regex and file contents passed in). The regex I used was

    (?<=STRING_BEFORE_VAULE)(.*)(?=STRING_AFTER_VALUE_UTIL_EOF\\s*)

For each section of the file I wanted I just called the Parser Class.

Thank you for your help.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top