0

I am working on java and I wanted to extract groups of matchings from a string, but I wonder how can I match the groups of numbers from a string.

For example, the string is "qwerty123834asdf3486dq123", I want to extract 123834 as the first group of matching and 3486 as a second group, then I need to save the first group in one variable and the second one in another variable, 123 is not required. I must do it with a grouping as 1st group of matching and 2nd, because the amount of numbers in group changes, thus I cannot take just substring.

I tried ([0-9])+, but it extracted all numbers, but I want to groups of matchings. Is it possible to do sth like this, ([0-9])+{1} to extract 123834 and ([0-9])+{2} to extract 3486

  • 12334 ? Are you sure ? – Tushar Gupta Apr 08 '17 at 11:44
  • 1
    http://stackoverflow.com/questions/2367381/how-to-extract-numbers-from-a-string-and-get-an-array-of-ints – Youcef LAIDANI Apr 08 '17 at 11:44
  • @Tushar thanks, I edited my post –  Apr 08 '17 at 11:48
  • "I tried ([0-9])+, but it gave all matchings, but I want to have groups of matchings." Please elaborate. It's unclear what you mean. – Patrick Parker Apr 08 '17 at 12:10
  • I have edited my post and I hope, it is much clearer now. –  Apr 08 '17 at 13:09
  • How is this question a duplicate of that?? Well here is what you need. `[^0-9]+([0-9]+)[^0-9]+([0-9]+)[^0-9]+.*` This will match with two groups of numbers. Can be shorter if you use the greedy flag. Then you don't need the [^0-9] parts. – Torge Apr 08 '17 at 23:36
  • @Torge Thank you very much, it worked, but since no one helped, I found another way to solve this issue: `word = word.replaceAll("[^0-9]+", " "); String[] array = word.trim().split(" "); String firstNumber=array[0]; String secondNumber=array[1];` –  Apr 09 '17 at 07:40

0 Answers0