0

My string is:

Frequency/FA ID VerifiedFA0 FAID5(125)/FA1 FAID7(175)/FA2 FAID1(476)

The regex I'm trying to create should extract these numbers:

125, 175, 476

I did it by looking at this example but there must be a better one.

myString.replaceAll(".+\\(([0-9]+)\\).+\\(([0-9]+)\\).+\\(([0-9]+)\\).*","$1,$2,$3")
Community
  • 1
  • 1
Ned
  • 1,055
  • 9
  • 34
  • 58
  • 1
    What is wrong with the solution you have? What exactly is your question? – Till Helge Jan 29 '13 at 20:07
  • Here is a java regex testing site: http://www.cis.upenn.edu/~matuszek/General/RegexTester/regex-tester.html – DwB Jan 29 '13 at 20:11
  • @Till Helge Helwig, I'm trying to find better one because i will need it soon for similar tasks. – Ned Jan 29 '13 at 20:22

3 Answers3

3

Rather than replacing everything that you don't need, you can use Pattern and Matcher class, to extract what you need.

The regex pattern to extract numbers between brackets would be: -

\(\d+\)

+ quantifier is used to match 1 or more repetition of digits. If you want to match just 3 digits, then you can use {3} quantifier with \d: - \(\d{3}\).

You can apply this regex pattern with Matcher#find() method to get all the numbers from that string. I leave the task of implementation to you.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
3

Check this out:

String s = "Frequency/FA ID VerifiedFA0 FAID5(125)/FA1 FAID7(175)/FA2 FAID1(476)";
Pattern patt = Pattern.compile("\\(\\d+\\)");
Matcher match = patt.matcher(s);
while(match.find()){
    System.out.println(match.group());
}
1

Slight change:

This finds exactly 3 digits inside of parentheses: ((\d\d\d))

The actual string value (in java) is: "(\\(\\d\\d\\d\\))"

Test on the Java RegEx Test page

isherwood
  • 58,414
  • 16
  • 114
  • 157
DwB
  • 37,124
  • 11
  • 56
  • 82