/*
* Copyright (C) Chaperon. All rights reserved.
* -------------------------------------------------------------------------
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*/
package net.sourceforge.chaperon.parser;
import net.sourceforge.chaperon.helpers.Decoder;
import net.sourceforge.chaperon.helpers.IntegerList;
/**
* Parser for regex expressions
*
* @author Stephan Michels
* @version CVS $Id: RegexParser.java,v 1.4 2002/05/06 16:22:56 benedikta Exp $
*/
public class RegexParser
{
//private boolean _debugmessages = false;
private IntegerList _stack = new IntegerList();
private IntegerList _newstack = new IntegerList();
/**
* Parse a string
*
* @param string String to test
* @param automate Regex automate
*
* @return Last postion, at which the parser was successful
*/
public int parse(char[] string, RegexAutomate automate)
{
return parse(string, automate, 0);
}
/**
* Search a postion, where the parser is successful
*
* @param string String to test
* @param automate Regex automate
*
* @return Next first position where the parser is successfull
* otherwise -1
*/
public int search(char[] string, RegexAutomate automate)
{
int position = 0;
while ((position < string.length)
&& (parse(string, automate, position) == -1))
position++;
if (position < string.length)
return position;
else
return -1;
}
/**
* Test a regex expresstion on a text at a special positon
*
* @param string String to test
* @param automate regex automate
* @param start Where the parser begin to test the expression
*
* @return Last postion, at which the parser was successful
*/
public int parse(char[] string, RegexAutomate automate, int start)
{
if (automate == null)
throw new NullPointerException("RegexAutomate is null");
if (automate.getSize() <= 0)
return -1;
int position = start;
int state;
int found = -1;
_stack.clear();
_newstack.clear();
_stack.push(0);
while ((!_stack.empty()) && (position <= string.length))
{
state = _stack.pop();
if (automate.isAcceptState(state))
found = position;
else if (automate.match(state, string, position))
{
if (automate.consumeCharacter(state))
_newstack.push(automate.getTransitions(state));
else
_stack.push(automate.getTransitions(state));
}
if (_stack.empty())
{
IntegerList temp = _newstack;
_newstack = _stack;
_stack = temp;
position++; // next character
}
}
return found;
}
/**
* Sets if the parser should output debug informations
*
* @param debug True, if the parser should output debug informations
*/
/*public void setDebug(boolean debug)
{
debugmessages = debug;
}*/
}