2

Here is my String 20161011 , I wanted to get the first String 20161011.

I am using the (^|\\s)([0-9]+)($|\\s) , however it doesn't work, could someone suggest the correct usage, btw the first String I wanted to retrieve is a date of the format yyyymmdd , I don't need to validate the date format as it comes pre validated.

3 Answers3

2

This should get you what you want:

^([0-9]{8}).*
  • ^ : matches the beginning of the line
  • ([0-9]{8}) : matches and captures the first 8 numeric digits
  • .* : matches the rest of the string and does not capture it. (you could probably leave this part off)
StvnBrkdll
  • 3,924
  • 1
  • 24
  • 31
1

The regex $(\d{8})\. would work on your sample. However, it's possible that you really want to split the string as described in this answer. This would give you access to each number, not just the first. It's also probably a bit faster.

Dan
  • 10,531
  • 2
  • 36
  • 55
  • My String changes dynamically each time, in the next occurence it may be 201610110909201 in the event that I am only interested with the first 8 digits from the string always –  Oct 27 '16 at 01:07
1

Here is how you can achieve this,

    Pattern r = Pattern.compile("\\d{8}+");
    Matcher m = r.matcher("12345678.231610.01234567");
    String str = "";
    if (m.find()) {
        // Only stores first occurence, occuring at any index of string.
        str = m.group();
    }
hashmap
  • 400
  • 1
  • 9