Is pattern match a good way to solve this problem?

I want to get all the numerical constants from a line of java statement. Numerical constants here refer to

1. int

2. float

3.double

For a example,

by running the method on the statement

"i = 232; f = 23.123f; c= f2h; int aa_2, b$99 ",

we should get 232, 23.123f and f2h but not 2 and 99.

How can I do that?

It seems to me that pattern match will not do the job well, am I right?

[444 byte] By [since81a] at [2007-10-2 23:56:49]
# 1
And what if you had this?"2 = 27; int 137"If your answer is that only 27 is a numerical constant then you need a parser that's aware of some sort of syntax.
DrClapa at 2007-7-14 16:43:33 > top of Java-index,Other Topics,Algorithms...
# 2

Thanks for the reply, Drclap.

Could you please give me an example? I have no idea about how to use a java parser to do this job.

By the way, I assume the input java statement is correct, so " 2 =27; int 227" wil never be considerred.

Thanks again.

Message was edited by:

since81

since81a at 2007-7-14 16:43:33 > top of Java-index,Other Topics,Algorithms...
# 3

> It seems to me that pattern match will not do the job

> well, am I right?

It looks ugly but

String line = "i = 232; f = 23.123f; c= f2h; int aa_2, b$99 ";

Pattern pattern = Pattern.compile("((?<=i ?= ?)\\d+|(?<=f ?= ?)\\d*(\\.\\d*)f|(?<=c ?= ?)[0-9a-f]+h)");

Matcher matcher = pattern.matcher(line);

while (matcher.find())

{

System.out.println(matcher.group(1));

}

and as DrClap points out there is room for ambiguity.

I bet "uncle_alice" could do better.

sabre150a at 2007-7-14 16:43:33 > top of Java-index,Other Topics,Algorithms...
# 4
sabre150, thanks for the post.Sorry, I may not discribe my question clearly. The string "i = 232; f = 23.123f; c= f2h; int aa_2, b$99 ";is just an example. The input for the desired function could be any legal java statement.
since81a at 2007-7-14 16:43:33 > top of Java-index,Other Topics,Algorithms...
# 5
> is just an example. The input for the desired> function could be any legal java statement.Then you need a Java parser, not regex.
sabre150a at 2007-7-14 16:43:33 > top of Java-index,Other Topics,Algorithms...
# 6
May I know how? There are lots of Java parsers and parser generators. I spent hours on reading docs but still have not idea about sovle my problem. I do need some guidance!
since81a at 2007-7-14 16:43:33 > top of Java-index,Other Topics,Algorithms...
# 7
Google for javacc - yes 'cc'.
sabre150a at 2007-7-14 16:43:33 > top of Java-index,Other Topics,Algorithms...
# 8
and here is a grammar for it http://cobase-www.cs.ucla.edu/pub/javacc/java1.4.jjmatfud
matfuda at 2007-7-14 16:43:33 > top of Java-index,Other Topics,Algorithms...