Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

regular expression  RSS feed

 
dale con
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello

I'm trying to write a regex that will check a string contains only numbers or only numbers and a + at the beginning

This will check for all numbers

String s= "0123456789";
boolean isValid = s.matches("\\d*");

But if i put a + in the string and do this
String s= "+0123456789";
boolean isValidPhone = phone.matches("\\+\\d*");

This will work, but what i want is to check a '+' at the start and rest are numbers or check string contains just numbers

If i do this
String s= "0123456789";
boolean isValidPhone = phone.matches("\\+\\d*");

It will fail becuae it hasn't got the '+', but i want it to be true cos the string is all numbers


Anyone help me out
 
Nigel Browne
Ranch Hand
Posts: 704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you need to write your expression as follows:
The ?+ means once or not at all, check out the API documentation for the java.util.regex.Pattern class
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, a bit of business: with 57 posts, you're surely aware of ournaming policy, which requires that you use a full, real (sounding) first and last name for
your display name. Joke names aren't OK. You can change your display name here. Thanks!


Now, as to your question: the "*" metacharacter means "zero or more", but there's also "+" (one or more) and "?" (0 or 1). You want to use this last one: "\\+?\\d*" .
 
dale con
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your help
 
Nigel Browne
Ranch Hand
Posts: 704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In response to Ernest's post, Java supports three quantifier types greedy, reluctant, and possessive.
Greedy quantifiers try to match as much as possible while their reluctant counterparts (with ? at the end) try to match the least required to fulfill a match.
What this means is that a greedy quantifier will try to match the entire line whether or not a successful match has occurred. Of course this method of quantification can turn into real performance overhead when the target text is large.
Reluctant (or lazy) quantifiers quit as soon as a successful match occurs without bothering to run through the entire line.
Possessive quantifiers (with + appended) are useful in optimizing the match operations since they don't keep the prior match states around.
So in other words there are three answers to your orginal question.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!