• Post Reply Bookmark Topic Watch Topic
  • New Topic

Pattern for phone number which are only digits or having a whitespace/dash after 3 numbers  RSS feed

 
Jacob Sonia
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Could anyone explain me this pattern for the scenario mentioned in the subject line:


String pattern = "\\d\\d\\d([,\\s])?\\d\\d\\d\\d";
 
Andrew Monkhouse
author and jackaroo
Marshal Commander
Posts: 12156
256
C++ Firefox Browser IntelliJ IDE Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you looked at what each of these mean in the Pattern class?

If so, what part of the regular expression are you having difficulty understanding?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
\\d\\d\\d - 3 digits

[,\\s] - a comma or whitespace character (it should be a dash not a comma)
() - thèse don't buy anything
? - optional (so 7 consecutive digits are ok)

\\d\\d\\d\\d - four digits

Also it would be better to write \\d{3} rather than list them all out.
 
Andrew Monkhouse
author and jackaroo
Marshal Commander
Posts: 12156
256
C++ Firefox Browser IntelliJ IDE Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeanne Boyarsky wrote:() - thèse don't buy anything

The only thing that the brackets buy you is that they become a capturing group. That is, if all you care about is finding out what the delimiter (if any) is, then by putting the [,\\s] inside brackets - ([,\\s]) - you will be able to find out what was in the line. Again - the Pattern class has more information.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!