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

Struggeling with regexp

 
Egil Poma
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need a regexp that can identify phone numbers based on how they are formated. They must be only digits, and can be formated like this:
12345678
123 45 678
12 34 56 78

I've created the following pattern that does this:


BUT: I've found one bug I don't know how to solve:
If the user enters a phone number consisting of more than 8 digits after each other, my regexp picks up only the 8 first digits. I want the regexp to identify the phone number only if it's exactly 8 digits after each other.



Any suggestions?

Thanks!
[ October 09, 2007: Message edited by: Egil Poma ]
 
Rob Spoor
Sheriff
Pie
Posts: 20380
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Add ^ to the start and $ to the end.
^ means the start of the string and $ means the end of the string.

So "abc" will look for any occurrence of "abc", where "^abc" will look only for "abc" at the start, "abc$" will look only for "abc" at the end, and "^abc$" will only match the exact string "abc".
 
Egil Poma
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lets say my input is:
String input = "12345678 blah blah";

I want to only get the phone number.

I tried to add ^ to the start and $ to the end of my pattern, but it doesn't seem to work: "^\\d{8}$"

What am I missing?
 
Egil Poma
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It seem this pattern does what I need
"\\b(\\d{8})\\b"
 
Henry Wong
author
Marshal
Pie
Posts: 20835
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Egil Poma:
It seem this pattern does what I need
"\\b(\\d{8})\\b"


Really?!? Does it work for some of the examples in your original post? Such as...


123 45 678
12 34 56 78


Henry
 
Egil Poma
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I changed the pattern mentioned in the first post to this:
"\\b(\\d{3} \\d{2} \\d{3})\\b|\\b(\\d{8})\\b|\\b(\\d{2} \\d{2} \\d{2} \\d{2})\\b"

The pipes separates each phone "format".
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic