Reputation: 153
I'm writing a program where I need to read a text file and extract some specific strings, the text is written in DOT language and this is an example of the file:
digraph G {
node [shape=circle];
0 [xlabel="[]"];
1 [xlabel="[[Text]]"];
0 -> 1 [label="a"];//this
1 -> 2 [label="ab"];//this
1 -> 3 [label="123"];//this
}
I want to ignore everything but the lines that have the structure of the commented lines (by //this
);
Then split every line to three parts, i.e.:
1 -> 2 [label="ab"];
saved as a list of strings (or array ...):
[1,2,ab]
I tried a lots with regex
but I couldn't get the expected results.
Upvotes: 2
Views: 75
Reputation: 626747
Here is the regex you can use:
(?m)^(\d+)\s+->\s+(\d+)\s+\[\w+="([^"]*)"];\s*//[^/\n]*$
See regex demo.
All the necessary details are held in Group 1, 2 and 3.
See Java code:
String str = "digraph G {\nnode [shape=circle];\n0 [xlabel=\"[]\"];\n1 [xlabel=\"[[Text]]\"];\n0 -> 1 [label=\"a\"];//this\n1 -> 2 [label=\"ab\"];//this\n1 -> 3 [label=\"123\"];//this\n}";
Pattern ptrn = Pattern.compile("(?m)^(\\d+)\\s+->\\s+(\\d+)\\s+\\[\\w+=\"([^\"]*)\"\\];\\s*//[^/\n]*$");
Matcher m = ptrn.matcher(str);
ArrayList<String[]> results = new ArrayList<String[]>();
while (m.find()) {
results.add(new String[]{m.group(1), m.group(2), m.group(3)});
}
for(int i = 0; i < results.size(); i++) { // Display results
System.out.println(Arrays.toString(results.get(i)));
}
Upvotes: 1
Reputation: 1892
IF you are guaranteed that the line will always be in the format of a -> b [label="someLabel"];
then I guess you can use a bunch of splits to get what you need:
if (outputLine.contains("[label=")) {
String[] split1 = outputLine.split("->");
String first = split1[0].replace(" ", ""); // value of 1
String[] split2 = split1[1].split("\\[label=\"");
String second = split2[0].replace(" ", ""); // value of 2
String label = split2[1].replace("\"", "").replace(" ", "").replace("]", "").replace(";", ""); // just the label
String[] finalArray = {first, second, label};
System.out.println(Arrays.toString(finalArray)); // [1, 2, ab]
}
Seems clunky. Probably a better way to do this.
Upvotes: 1