Trivial regex problem
I'm sure this is a very easy regular expression, I just can't seem to get it to work the way I want it to. Basically, I want to check the first character of a string and see if it matches either 0, 1 or 2.
String str = "2 Invalid Server Response"
str.matches("[0-2]");
I don't know how to check the first character and ignore the rest of the string. Is there a way to do this wihout first making a substring of the first character?
Thanks
[472 byte] By [
Rob-UKa] at [2007-11-26 20:19:57]

The regex is"^[0-2].*"^ = the beginning of the line,[0-2] = followed by 0, 1 or 2,. = any character,* = zero or more times
> The regex is"^[0-2].*"
> ^ = the beginning of the line,
> [0-2] = followed by 0, 1 or 2,
> . = any character,
> * = zero or more times
The ^ is not required in Java regex because the whole has to match so you can just use the regex "[0-2].*" .
> > The regex is "^[0-2].*"
> > ^ = the beginning of the line,
> > [0-2] = followed by 0, 1 or 2,
> > . = any character,
> > * = zero or more times
>
> The ^ is not required in Java regex because the whole
> has to match so you can just use the regex "[0-2].*" .
Yes, of course. That was silly...
Thanks.
Edit:
Why did you specifically write "in Java regex"? Are there other regexes where you need to specify the beginning of a line in this case?
> > > The regex is "^[0-2].*"
> > > ^ = the beginning of the line,
> > > [0-2] = followed by 0, 1 or 2,
> > > . = any character,
> > > * = zero or more times
> >
> > The ^ is not required in Java regex because the
> whole
> > has to match so you can just use the regex
> "[0-2].*" .
>
> Yes, of course. That was silly...
> Thanks.
>
> Edit:
> Why did you specifically write "in Java regex"? Are
> there other regexes where you need to specify
> the beginning of a line in this case?
I wouldn't say "in Java regex." I'd say "in Java's matches method."
bsh % str = "123456789";
bsh % str.matches("5");
<false>
bsh % p = Pattern.compile("5");
bsh % m = p.matcher(str);
bsh % m.find();
<true>
> > Why did you specifically write "in Java regex"?
> Are
> > there other regexes where you need to
> specify
> > the beginning of a line in this case?
>
> Atleast in lex RE design we don't have to
Don't have to "in Java regex" either, depending on which method you use.