aspose file tools*
The moose likes Java in General and the fly likes Struggeling with regexp Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Struggeling with regexp" Watch "Struggeling with regexp" New topic
Author

Struggeling with regexp

Egil Poma
Ranch Hand

Joined: Nov 23, 2002
Posts: 40
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

Joined: Oct 27, 2005
Posts: 19761
    
  20

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".


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Egil Poma
Ranch Hand

Joined: Nov 23, 2002
Posts: 40
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

Joined: Nov 23, 2002
Posts: 40
It seem this pattern does what I need
"\\b(\\d{8})\\b"
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18990
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Egil Poma
Ranch Hand

Joined: Nov 23, 2002
Posts: 40
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
 
subject: Struggeling with regexp