Reputation: 896
For part of my Java assignment I'm required to select all records that have a certain area code. I have custom objects within an ArrayList
, like ArrayList<Foo>
.
Each object has a String phoneNumber variable. They are formatted like "(555) 555-5555"
My goal is to search through each custom object in the ArrayList<Foo>
(call it listOfFoos
) and place the objects with area code "616" in a temporaryListOfFoos
ArrayList<Foo>
.
I have looked into tokenizers, but was unable to get the syntax correct. I feel like what I need to do is similar to this post, but since I'm only trying to retrieve the first 3 digits (and I don't care about the remaining 7), this really didn't give me exactly what I was looking for. Ignore parentheses with string tokenizer?
What I did as a temporary work-around, was...
for (int i = 0; i<listOfFoos.size();i++){
if (listOfFoos.get(i).getPhoneNumber().contains("616")){
tempListOfFoos.add(listOfFoos.get(i));
}
}
This worked for our current dataset, however, if there was a 616 anywhere else in the phone numbers [like "(555) 616-5555"] it obviously wouldn't work properly.
If anyone could give me advice on how to retrieve only the first 3 digits, while ignoring the parentheses, I would greatly appreciate it.
Upvotes: 1
Views: 514
Reputation: 69339
You could use a regular expression as shown below. The pattern will ensure the entire phone number conforms to your pattern ((XXX) XXX-XXXX) plus grabs the number within the parentheses.
int areaCodeToSearch = 555;
String pattern = String.format("\\((%d)\\) \\d{3}-\\d{4}", areaCodeToSearch);
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(phoneNumber);
if (m.matches()) {
String areaCode = m.group(1);
// ...
}
Whether you choose to use a regular expression versus a simple String lookup (as mentioned in other answers) will depend on how bothered you are about the format of the entire string.
Upvotes: 0
Reputation:
I think what you need is a capturing group. Have a look at the Groups and capturing section in this document.
Once you are done matching the input with a pattern (for example "\((\\d+)\) \\d+-\\d+"
), you can get the number in the parentheses using a matcher
(object of java.util.regex.Matcher
) with matcher.group(1)
.
Upvotes: 1
Reputation: 5122
You have two options:
value.startsWith("(616)")
or,"^\(616\).*"
The first option will be a lot quicker.
Upvotes: 2
Reputation: 4877
areaCode = number.substring(number.indexOf('(') + 1, number.indexOf(')')).trim()
should do the job for you, given the formatting of phone numbers you have.
Or if you don't have any extraneous spaces, just use areaCode = number.substring(1, 4)
.
Upvotes: 1