• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to extract a group of digits in a String?  RSS feed

 
Sam Samson
Ranch Hand
Posts: 63
IntelliJ IDE Java jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Given the String "xyz_Q1229_F1224", how can I extract the 1229 from it?

I tried:
https://ideone.com/SiCrRs



But this is returning '9'. Why is it returning the last digit of the first digit-group 1229?

edit:
Argh, found it -> Q(\\d+)
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done and thank you for telling us the solution.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not just use the substring method? It's much simpler and easier to understand.

Or are there some restrictions that you haven't clearly explained? (hint hint)

My larger point is that you should get in the habit of clearly explaining what you need to do. An example is always great, but it doesn't define the problem. Given your description, there is no reason that substring(5,9) wouldn't work (assuming I have my indexes correct).

If the number of digits can vary, you should include that in your problem description.

Just my 2cents
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Answering the original question, even though it is no longer needed...

Sam Samson wrote:
But this is returning '9'. Why is it returning the last digit of the first digit-group 1229?


When a regular expression repeats a capturing group (for completion of the match), only the last iteration is returned for the capturing group.

Henry
 
Sam Samson
Ranch Hand
Posts: 63
IntelliJ IDE Java jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
fred rosenberger wrote:Why not just use the substring method? It's much simpler and easier to understand.

Or are there some restrictions that you haven't clearly explained? (hint hint)

My larger point is that you should get in the habit of clearly explaining what you need to do. An example is always great, but it doesn't define the problem. Given your description, there is no reason that substring(5,9) wouldn't work (assuming I have my indexes correct).

If the number of digits can vary, you should include that in your problem description.

Just my 2cents


Jep, sorry, the number of digits can vary.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!