Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

I'm trying

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

And the if clause is never called.

like image 542
Matt Smith Avatar asked Aug 02 '13 14:08

Matt Smith


People also ask

How do you check if a string contains numbers and letters?

The RegExp test() Method To check if a string contains only letters and numbers in JavaScript, call the test() method on this regex: /^[A-Za-z0-9]*$/ . If the string contains only letters and numbers, this method returns true . Otherwise, it returns false .

How do you check if a string ends with a number?

To check if a string ends with a number, call the test() method on a regular expression that matches one or more numbers at the end a string. The test method returns true if the regular expression is matched in the string and false otherwise.

Which of following method is used to check if string is start with particular regex or not?

I really recommend using the String. StartsWith method over the Regex. IsMatch if you only plan to check the beginning of a string.

How do you search for a regex pattern at the beginning of a string?

The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.


1 Answers

Don't use a regex:

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

(see Character.isDigit())

like image 196
arshajii Avatar answered Sep 21 '22 06:09

arshajii