10

I'm trying:

String string = "123456";    
if(string.startsWith("[0-9]") && string.endsWith("[0-9]")){
    //code
}

And the if clause is never called.

4
  • 5
    What led you to believe it's a regex argument? Commented Aug 2, 2013 at 14:36
  • Where is the variable name? Commented Aug 2, 2013 at 14:37
  • 1
    Is it just me or is there no question in the post? Commented Aug 2, 2013 at 14:39
  • 1
    We have assumed the missing last word is: "Why?" Commented Aug 2, 2013 at 14:40

5 Answers 5

26

Don't use a regex:

Character.isDigit(string.charAt(0)) && 
                              Character.isDigit(string.charAt(string.length()-1))

(see Character.isDigit())

Sign up to request clarification or add additional context in comments.

3 Comments

I think that this is the more faster way.
I agree, no regex needed.
@MattSmith Are you sure it's from this line? There are no cases where this should cause an IllegalStateException. Try checking the surrounding code.
9

The methods startsWith() and endsWith() in class String accept only String, not a regex.

1 Comment

Very true, but as it stands this is more of comment than an answer. How would you suggest they "...[check] if a string starts and ends with number characters."?
4

You can use the matches method on String thusly:

public static void main(String[] args) throws Exception {
    System.out.println("123456".matches("^\\d.*?\\d$"));
    System.out.println("123456A".matches("^\\d.*?\\d$"));
    System.out.println("A123456".matches("^\\d.*?\\d$"));
    System.out.println("A123456A".matches("^\\d.*?\\d$"));
}

Output:

true
false
false
false

1 Comment

Thank you for the solution, I want to use the same concept in javascript, however when I use ^\\d.*?\\d$ for a string, it does not work. For string 3rd it should give false and for strings 3 or 3(white spaces) the output should be true. Any guidance would be much appreciated.
3

You can use:

String string = "123test123";
if(string.matches("\\d.*\\d"))
{
    // ...
}

1 Comment

@ProgramFOX You actually don't need the anchors with matches().
-1

Please follow the code snippet.

String variableString = "012testString";
Character.isDigit(string.charAt(0)) && variableString.Any(c => char.IsUpper(c));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.