• Post Reply Bookmark Topic Watch Topic
  • New Topic

Regular expressions...  RSS feed

 
Jack Bercy
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a string, and I want to test if it begins with "RD".

Here's my test code :


if (Pattern.matches("^RD", "RD0000245")){
log.debug("Test matches...");
} else {
log.debug("Test doesn't match...");
}


I also tried :

if (Pattern.matches("^RD.*", "RD0000245")){
log.debug("Test matches...");
} else {
log.debug("Test doesn't match...");
}


Both log "Test doesn't match"...

Why ?

Thanks !
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why don't you use String.startsWith()?
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the JavaDoc for matches()...

true if, and only if, the entire input sequence matches this matcher's pattern


This means "^RD" should not work, but "^RD.*" should work. Furthermore, since it is the entire pattern, "RD.*" should also work.

BTW, I agree. Why don't you just use startsWith() ?

Henry
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first test fails because matches() requires that the pattern match the entire String. It seems you understand this on some level given your second test. As well, the second test passes for me in JDK 1.5.0, as it should.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!