0

I have a list of phone numbers and other text such as the following:

+1-703-535-1039  +1-703-728-8382 +1-703-638-1039  +1-703-535-1039 

And I'm trying to match just the area code and first 3 digits of the number.

Currently I'm using the following Regex:

\d{3}-\d{3}

But it only returns the first match instead of all matches.

Pls see this link for reference:

https://regex101.com/r/oO1lI9/1

Cœur
  • 37,241
  • 25
  • 195
  • 267
Kay Mart
  • 65
  • 3
  • 3
    Did you actually try this with Java? In regex101, if you want all the matches use `g` modifier. – Codebender Aug 06 '15 at 03:43
  • I'm voting to close this question as off-topic because this is one of those questions http://meta.stackoverflow.com/questions/285733/should-give-me-a-regex-that-does-x-questions-be-closed/ – sandrstar Aug 06 '15 at 06:04

1 Answers1

1

In regex101, use global g flag to get all matches

Demo

To get all matches in Java:

Pattern pattern = Pattern.compile("(\d{3}-\d{3})");
Matcher matcher = pattern.matcher("+1-703-535-1039  +1-703-728-8382 +1-703-638-1039  +1-703-535-1039");

// Find all matches
while (matcher.find()) {
    // Get the matching string
    String match = matcher.group();
}

Reference

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • The original answer targeted the question, not the edited answer. However, I realized I need the area code and the first 3 digits WITHOUT the dash (-) in between. I tried this: `\d{3}(?=-)\d{3}` (positive look ahead) but I did not get any matches.. – Kay Mart Aug 06 '15 at 03:57
  • @KayMart, `(?=-)\d{3}` matches three digits when the first digit is also a dash, which can never be the case. Lookaheads match without consuming output, but what you seem to want is for the output of the match not to include the dashes. Your best bet is to strip the dashes from the output as a second step. – Mike Samuel Aug 06 '15 at 03:59
  • 3
    There's no such thing as a "global" flag in java regex. – Bohemian Aug 06 '15 at 04:04