I’m working on writing a simple Prolog interpreter in Java.
How can I find the last character index of the first element either the head element or the tail element of a string in “List Syntax”?
List Syntax looks like:
(X)
(p a b)
(func (func2 a) (func3 X Y))
(equal eve (mother cain))
The head for each of those strings in order are:
Head: “X”, Index: 1
Head: “p”, Index: 1
Head: “func”, Index: 4
Head: “equal”, Index: 5
Basically, I need to match the string that immediately follows the first “(” and ends either with a space or a closing “)”, whichever comes first. I need the character index of the last character of the head element.
How can I match and get this index in Java?
Brabster’s solution is really close. However, consider the case of:
((b X) Y)
Where the head element is (b x). I attempted to fix it by removing “(” from the scanner delimiters but it still hiccups because of the space between “b” and “x”.
Similarly:
((((b W) X) Y) Z)
Where the head is (((b w) x) Y).
Java’s Scanner class (introduced in Java 1.5) might be a good place to start.
Here’s an example that I think does what you want (updated to include char counting capability)
Output:
It’s not a very elegant solution, but regexes can’t count (i.e. brackets). I’d be thinking about using a parser generator if there’s any more complexity in there 🙂