[antlr-interest] Reading a string of fixed size
Edwards, Waverly
Waverly.Edwards at genesys.com
Mon Aug 27 02:52:30 PDT 2007
Here is something that is functional.
I'm a newbie at all of this, ANTLR and Regular expressions so don't take this as the Gospel. You'll want to check this out carefully.
I didn't even know you could do this: Integer.parseInt($NUMBER.text)
If you can, this code could be shorter and I will have learned something else useful.
W.
grammar TESTCAMISTRING;
fragment
Letter : 'a'..'z' | 'A'..'Z' ;
fragment
Digit : '0'..'9' ;
fragment
AlphaNum : Letter | Digit ;
prog : start+ ;
start : CAMI_STRING
;
NEWLINE : ('\r\n'|'\r'|'\n') ;
CAMI_STRING : Digit+ ':' Letter AlphaNum*
{
String wholeStr,numStr,fixLenStr;
int colonLoc, num;
boolean validate;
wholeStr = getText().toString();
colonLoc = wholeStr.indexOf(":");
numStr = wholeStr.substring(0, colonLoc);
num = Integer.parseInt(numStr);
fixLenStr = wholeStr.substring(colonLoc+1);
validate = (num == fixLenStr.length() );
if ( validate == true )
System.out.println(numStr + "," + fixLenStr);
else
System.out.println("ERROR: num:Str length mismatch");
};
-----Original Message-----
From: antlr-interest-bounces at antlr.org [mailto:antlr-interest-bounces at antlr.org] On Behalf Of Alexandre Hamez
Sent: Monday, August 27, 2007 3:33 AM
To: antlr-interest at antlr.org
Subject: [antlr-interest] Reading a string of fixed size
Hi everybody,
I need to read a string of a fixed size. For example : '5:abcde'.
The size of the string to be read is given by the number before the ':'. So I've written the following:
CAMI_STRING
:
NUMBER ':'
{
// Get the current position in stream
int start = input.getCharPositionInLine();
// Computing the position of the last character of the STRING to be read
int end = start + Integer.parseInt($NUMBER.text) - 1;
// Set the value of the returned value to STRING
setText(input.substring(start,end));
// Update the position in the stream
input.seek(end+1);
}
;
NUMBER
:
'0'..'9'+
;
It works quite well until the string to be read contains a number itself. Have you an idea on this problem? Thanks for you help!
------------------------------------------------------------------------
---
Alexandre Hamez LIP6 - MoVe / EPITA - LRDE
LIP6: tel: +33 1 44 27 31 92 / Bureau 818
104 Avenue du Président Kennedy 75016 Paris http://www-src.lip6.fr/~Alexandre.Hamez
More information about the antlr-interest
mailing list