Matt Smith
Matt Smith

Reputation: 975

Checking if a string starts and ends with number characters using regex

I'm trying:

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

And the if clause is never called.

Upvotes: 10

Views: 37079

Answers (5)

Md. Mostafizur Rahman
Md. Mostafizur Rahman

Reputation: 93

Please follow the code snippet.

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

Upvotes: -1

Boris the Spider
Boris the Spider

Reputation: 61138

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

Upvotes: 4

Сашка724ая
Сашка724ая

Reputation: 682

You can use:

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

Upvotes: 3

arshajii
arshajii

Reputation: 129497

Don't use a regex:

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

(see Character.isDigit())

Upvotes: 26

arjacsoh
arjacsoh

Reputation: 9232

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

Upvotes: 9

Related Questions