• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Does String.startsWith() support multiple string?

 
Jack Bush
Ranch Hand
Posts: 235
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am currently having to use a number of separate ( String.startsWith("apple") || String.startsWith("orange") || String.startsWith("grape") .....) as opposed to the following regular expression:



Any suggestion?

Thanks a lot,

Jack
 
john price
Ranch Hand
Posts: 495
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



John Price
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@john:syntax error in your for loop!
 
Rob Spoor
Sheriff
Pie
Posts: 20609
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you only want to check for the presence, instead of also retrieving the value, you can use a regular expression in combination with String.matches. Check out the Javadoc page of java.util.regex.Pattern for more information. Don't forget to let your regex end with ".*", because String.matches looks for a match of the entire String.
 
Jack Bush
Ranch Hand
Posts: 235
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rob,

String.matches("(?:apple|orange|grape).*")

works as suggested.

Thank you,

Jack
 
Rob Spoor
Sheriff
Pie
Posts: 20609
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic