zwang
zwang

Reputation: 705

Regular Expression - Java not working

I have a line of Java code

System.out.println("...Somtime".matches("^[^a-zA-Z]"));

Which returns false. Why? Can any one help?

Upvotes: 0

Views: 120

Answers (2)

Manish Nagar
Manish Nagar

Reputation: 1046

String.matches("regex") 

This method will match the regex against the WHOLE string. If the string matches regex, it will return true and false otherwise

System.out.println("...Somtime".matches("^[^a-zA-Z]{3}[a-zA-Z]+"));

here for three dots you are using {3} and this return true

System.out.println("Somtime".matches("^[^a-zA-Z]"));

it return false

Upvotes: 3

Rohit Jain
Rohit Jain

Reputation: 213243

String#matches matches at both the ends, so your pattern should cover the complete string. And also you don't need to give those anchors (Caret - ^) at the beginning. It is implicit.

Now, since your first three characters matches - [^a-zA-Z], while the later characters matches - [a-zA-Z].

So, probably you want: -

"...Somtime".matches("[^a-zA-Z]{3}[a-zA-Z]+")

Upvotes: 5

Related Questions