Find character at the end of the string with regex
I have a simple regex that I cant get to work, it is supposed to check that the last character in a string is an integer.
String myString = "dst760.log.092211.233116";
if(myString.matches("\\d$")
{
do something
}
else
{
do something else
}
The format of the string changes but the only thing I want to check is the last character. I have tried a few iterations without any success here are a few of them ("[0-9]$")("^*.[\\d+]$") and few more that I cant remember.
Re: Find character at the end of the string with regex
You shouldn´t use matches( ... ) because it tries to match the entire String against the regular expression. Use find() and read the API documentation for the Matcher class.
kind regards,
Jos
Re: Find character at the end of the string with regex
Thanks for pointing me in the right direction, I will try find().
Re: Find character at the end of the string with regex
Quote:
Originally Posted by
samnjugu
Thanks for pointing me in the right direction, I will try find().
Of course you can also do without those nasty regular expressions; have a look:
Code:
boolean isLastDigit(String s) {
if (s == null || s.length() == 0) return false; // no last digit in here
char l= s.charAt(s.length()-1); // the last char
return Character.isDigit(c);
}
kind regards,
Jos
Re: Find character at the end of the string with regex
Hi Jos, I have been using a method almost exactly as yours, after having no success with the regex as for some reason my matcher class does not have a find() method. In my version since I check for null before calling this method I have just shrunk it to a oneliner.
Code:
static boolean lastCharIsDigit(String string)
{
return Character.isDigit(string.charAt(string.length() - 1));
}
Thanks for the help.