Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Problems with java.util.regex.Pattern) checking string for digits and letters

I have a task to check if a new string (login) complies some rules These are rules:

1. It has to be 1-20 symbols length
2. It may consist of digits, letters (a-z,A-Z), dots and "-"
3. The first symbol has to be a letter (a-z,A-Z)
4. It has to end with a letter or a digit

So i thought of using java.util.regex.Pattern, and I ran in some problems. Thats what i have:

    String login = "a.bc-.52";
    Pattern p1 = Pattern.compile("([a-zA-Z]{1}[a-zA-Z\\d.-]{0,18}[a-zA-Z\\d])");
    Matcher m1 = p1.matcher(login);
    boolean b = m1.matches();

I'm having trouble to check if string ends with a letter or a diggit. I think i could split the string and check its parts with different patterns, but something tells me, that it can be done easier.

I'm sorry if it is a dumb questions or i've made mistakes. Perhaps there is easier way, please tell me. Thank you

like image 550
netaholic Avatar asked Dec 29 '25 06:12

netaholic


2 Answers

^[a-zA-Z]{1}[a-zA-Z\d.-]{0,18}[a-zA-Z\d]$

^ <- ensures that the string begins with a letter

$ <- ensures that the string ends with a letter of digit

like image 187
Adam Sznajder Avatar answered Dec 31 '25 21:12

Adam Sznajder


What you are looking for is the dollar sign. Simple as that:

t$ --> ends in t

The opposite is ^

^a - starts with a

So in your case just add the dollar sign at the end.

like image 21
Eugene Avatar answered Dec 31 '25 20:12

Eugene