varsha reddy varsha reddy - 1 month ago 15
Java Question

Regex to find the first occurence of first 8 digits from a string in Java

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

I am using the (^|\s)([0-9]+)($|\s) , however it doesn't work, could some one 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

Answer

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)
Comments