简体   繁体   中英

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

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.

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)

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.

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM