Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

You have two options:

  1. Use value.startsWith("(616)") or,
  2. Use regular expressions with this pattern "^\(616\).*"

The first option will be a lot quicker.

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top