Regular Expression

T

the87boy

Why do this regular expression not work:
if (str.matches("^\\d*$") || str.matches("^\\d*" + dot + "$") ||
str.matches("^\\d*" + dot + "\\d*$")) {
return true;
} else {
return false;
}

dot is a string, who looks like this:
String dot = ",";

The 1st regular expression test if it is just a number
The 2nd regular expression test if it is a number and ends with a dot
The 3rd regular exression test if it is a dot sorrunded by numbers
It's only number (can be with a dot)

Can somebody tell me, what's wrong and maybe shorten it?
 
J

Jussi Piitulainen

Why do this regular expression not work:
if (str.matches("^\\d*$") || str.matches("^\\d*" + dot + "$") ||
str.matches("^\\d*" + dot + "\\d*$")) {
return true;
} else {
return false;
}

dot is a string, who looks like this:
String dot = ",";

The 1st regular expression test if it is just a number
The 2nd regular expression test if it is a number and ends with a dot
The 3rd regular exression test if it is a dot sorrunded by numbers
It's only number (can be with a dot)

Can somebody tell me, what's wrong and maybe shorten it?

It appears to work. It matches ",14" and "3," and "," in addition to
"314" and "3,14", though. You failed to give an example of a str that
you think should match and does not, or that you think should not
match and does.

"foo|bar|baz" matches "foo" or "bar" or "baz".
"foo,?bar" matches "foobar" or "foo,bar".

The anchors are redundant with .matches().
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top